파이썬3 바이블 - 제4장 연습문제

프리렉 - FREELEC

http://freelec.co.kr/book/catalogue_view.asp?UID=134

이강성저

1. s = 'spam'에서 다음 질문에 답하고 이유를 설명해 보자.

가) s[100]의 결과는 무엇인가?
나) s[1:100]의 결과는 무엇인가?
다) s[4:0]의 결과는 무엇인가?
In [1]:
s = 'spam'
In [2]:
s[100] # 인덱싱은 참조 범위를 넘어서면 IndexError가 발생한다.
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-2-fc22fdecfe9d> in <module>()
----> 1 s[100] # 인덱싱은 참조 범위를 넘어서면 IndexError가 발생한다.

IndexError: string index out of range
In [3]:
s[1:100]    # 슬라이싱이 참조 범위를 넘어서면 범위 내에서 처리한다.
Out[3]:
'pam'
In [4]:
s[4:0]     # 시작값보다 끝값이 더 작은 경우에는 공문자열이 리턴된다.
Out[4]:
''

2.

In [5]:
# 가)
s = 'Somewhere on the rainbow'
s.replace('on', 'over')
Out[5]:
'Somewhere over the rainbow'
In [6]:
# 나)
s = 'Sometimes, I feel like a motherless child.'
s.replace('.', '')
Out[6]:
'Sometimes, I feel like a motherless child'
In [7]:
# 다)
# 정규식에 관해서는 26장 참조

3.

In [8]:
s = '''Using Praat for Linguistic Research by Will Styler is a practical guidebook and information package designed to help you use the Praat phonetics software package more effectively in Phonetic or Phonological research. Although it was originally written in the Spring/Summer of 2011 for the 2011 Linguistic Institute's Praat workshop, it's now available for anybody who's interested.

The guidebook itself is a 60+ page compilation of walkthroughs, explanations, and tutorials explaining how to use Praat for a variety of measurements and tasks. Although the guide does start with "basic" tasks like opening sound files, measuring duration, formants, pitch, it also covers more "advanced" tasks like source-filter resynthesis, A1-P0 nasality measurement, formula manipulation of sounds and even Praat scripting.

Using Praat for Linguistic Research is completely free, and can be used for whatever purpose you see fit. However, the author does ask that any usage be accompanied with a link to this page, such that later users can download the most recent versions of the guide. The guide will be updated over time, both as Praat changes and as the author adds new information.

In addition to the guidebook, the author has also made available a collection of documents, presentations, scripts and sound files which, along with a short syllabus, formed the core of the LSA Praat workshop. The scripts are made freely available for use and code-cannibalism, and the sound files are free for use in teaching oneself to use Praat with the Guidebook and the syllabus/worksheet.

Using Praat for Linguistic Research is licensed under a Creative Commons Attribution ShareAlike (CC BY-SA) License. More information on this license is available here.

Any questions, comments, concerns or corrections should be sent to Will Styler, will (at) savethevowels (dot) org.'''
In [9]:
s.count('\n')   # 공백 라인 포함
Out[9]:
10
In [10]:
# 공백이 아닌 라인 수를 구하고 싶다면
len(list(filter(None, s.splitlines())))
Out[10]:
6

4.

In [11]:
s = '/usr/local/bin/python'
s.split('/')
Out[11]:
['', 'usr', 'local', 'bin', 'python']

5.

In [12]:
s = '/usr/local/bin/python'
In [13]:
parts = s.split('/')
'/'.join(parts[:-1]), parts[-1]
Out[13]:
('/usr/local/bin', 'python')
In [14]:
import os
os.path.split(s)
Out[14]:
('/usr/local/bin', 'python')

6.

In [15]:
s = 'spam ham'

ws = s.split()
ws.reverse()
' '.join(ws)
Out[15]:
'ham spam'

7.

In [16]:
s = 'spam'
s[0]       # 'spam'의 첫 번째 문자
Out[16]:
's'
In [17]:
s[0][0]    # s[0] == 's'  이므로 연속으로 적용해도 첫 문자 's'가 나옴. 파이썬은 문자 자료형이 없고 모두 문자열 자료형임
Out[17]:
's'

8.

In [18]:
s = 'spam Spam SpaM egg eGG Egg ham hAm'

s.lower().count('spam')
Out[18]:
3

9.

In [19]:
s = 'We propose programming in to start by making it possible to teach Python, an existing scripting language, and to focus on creating a new development environment and teaching materials for it.'
In [20]:
# 소문자로
s1 = s.lower()
In [21]:
# 알파벳을 제외한 모든 문자 제거
import re

s2 = re.sub('[^a-z]', ' ', s1)
s2
Out[21]:
'we propose programming in to start by making it possible to teach python  an existing scripting language  and to focus on creating a new development environment and teaching materials for it '
In [22]:
# 각 단어를 순서대로 출력
ws = s2.split()
ws.sort()
ws
Out[22]:
['a',
 'an',
 'and',
 'and',
 'by',
 'creating',
 'development',
 'environment',
 'existing',
 'focus',
 'for',
 'in',
 'it',
 'it',
 'language',
 'making',
 'materials',
 'new',
 'on',
 'possible',
 'programming',
 'propose',
 'python',
 'scripting',
 'start',
 'teach',
 'teaching',
 'to',
 'to',
 'to',
 'we']

10.

In [23]:
import collections

collections.Counter(ws)
Out[23]:
Counter({'to': 3, 'it': 2, 'and': 2, 'development': 1, 'teaching': 1, 'scripting': 1, 'an': 1, 'by': 1, 'a': 1, 'materials': 1, 'propose': 1, 'for': 1, 'existing': 1, 'python': 1, 'possible': 1, 'focus': 1, 'start': 1, 'in': 1, 'new': 1, 'programming': 1, 'on': 1, 'making': 1, 'environment': 1, 'we': 1, 'language': 1, 'teach': 1, 'creating': 1})
In [24]:
sorted(collections.Counter(ws).items())
Out[24]:
[('a', 1),
 ('an', 1),
 ('and', 2),
 ('by', 1),
 ('creating', 1),
 ('development', 1),
 ('environment', 1),
 ('existing', 1),
 ('focus', 1),
 ('for', 1),
 ('in', 1),
 ('it', 2),
 ('language', 1),
 ('making', 1),
 ('materials', 1),
 ('new', 1),
 ('on', 1),
 ('possible', 1),
 ('programming', 1),
 ('propose', 1),
 ('python', 1),
 ('scripting', 1),
 ('start', 1),
 ('teach', 1),
 ('teaching', 1),
 ('to', 3),
 ('we', 1)]
In [25]:
# 직접 계산하는 방법
cnt = {}
for w in ws:
    if w in cnt:
        cnt[w] += 1
    else:
        cnt[w] = 1
sorted(cnt.items())
Out[25]:
[('a', 1),
 ('an', 1),
 ('and', 2),
 ('by', 1),
 ('creating', 1),
 ('development', 1),
 ('environment', 1),
 ('existing', 1),
 ('focus', 1),
 ('for', 1),
 ('in', 1),
 ('it', 2),
 ('language', 1),
 ('making', 1),
 ('materials', 1),
 ('new', 1),
 ('on', 1),
 ('possible', 1),
 ('programming', 1),
 ('propose', 1),
 ('python', 1),
 ('scripting', 1),
 ('start', 1),
 ('teach', 1),
 ('teaching', 1),
 ('to', 3),
 ('we', 1)]

11.

In [26]:
s = 'spam'
r = ''
i = len(s)
while i > 0:
    i -= 1
    r += s[i]
r    
Out[26]:
'maps'

12.

In [27]:
s = 'spam'
L = []
for c in s:
    L.insert(0, c)
''.join(L)    
Out[27]:
'maps'
In [28]:
# 더 쉽고 간단한 방법
s = 'spam'
s[::-1]
Out[28]:
'maps'

13.

In [29]:
passwd = '''noriko:x:524:500:유화정:/home/noriko:/bin/bash
sky1004mu:x:525:500:김청:/home/sky1004mu:/bin/bash
hyeyroung:x:526:500:이혜령:/home/hyeyroung:/bin/bash
muu20:x:527:500:이현복:/home/muu20:/bin/bash'''
In [30]:
for line in passwd.splitlines():
    fields = line.split(':')
    if len(fields) >= 5:
        print (fields[4])
유화정
김청
이혜령
이현복

14.

In [31]:
t = ('a', 'b', 'c')
'|'.join(t)
Out[31]:
'a|b|c'

15.

In [32]:
s = """
<body bgcolor="#FFFFFF">
Click <a href="http://www.python.org/"> Here </a>
To connect to the most powerful tools in the world.
</body>
</html>
"""
In [33]:
import re

s1 = re.sub('<.*?>', '', s)
print(s1)


Click  Here 
To connect to the most powerful tools in the world.




16.

In [34]:
import urllib.request
s = urllib.request.urlopen('http://www.python.org/').read( )
print(s[:100])  # 일부만 출력해보자
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm'

In [35]:
type(s)   # 웹에서 가져온 객체는 문자열이 아닌 바이트(bytes) 자료형임
Out[35]:
builtins.bytes
In [36]:
type(s.decode())  # 이 것을 문자열(str)로 바꾸려면 decode() 메서드 적용
Out[36]:
builtins.str
In [37]:
import re

s1 = re.sub('<.*?>', '', s.decode(), flags=re.DOTALL).strip()

print (s1)
Python Programming Language &ndash; Official Website
  
  
  
  
  
  
  
  
  
  
  
  

  
  
  
  
  

  

  

  

  

  

  

  

  
  
  





  
  
    
  
  
  
  
  
  
    
    
      
        
          
          
          
          
          
          Advanced Search
        
      
    
    
  

  
    
    
      
            
          About
        
            
          News
        
            
          Documentation
        
            
          Download
        
            
          下载
        
            
          Community
        
            
          Foundation
        
            
          Core Development
        
      
    

    
      Help

      Package Index

      Quick Links (2.7.6)

	
	  Documentation
	  Windows Installer
	  Source Distribution
	
      Quick Links (3.3.2)

	
	  Documentation
	  Windows Installer
	  Source Distribution
	
      Python Jobs

      Python Merchandise

    Python Wiki
    Python Insider Blog
    Python 2 or 3?
    Help Fund Python
    
      
    
    
            
    
    
       Non-English Resources
    
    
        
            
                Python Release Schedule iCal Calendar
            
        
    
    
        
            
                Python Events iCal Calendar
            
        
        Add an event to this calendar.
    
    
        
            
                Python User Group iCal Calendar
            
        
        Add an event to this calendar.
    
  

  
    
      
        
  

        Python Programming Language &ndash; Official Website
	
          

          
            Support the Python Community
            Help the Python community
               by becoming an associate member or 
               making a one-time donation.
	  
          
          
           Python 3 Poll
           I wish there was Python 3 support in
           
             
             (enter PyPI package name)
             
               
               Results
             
           
          

          
           
            NASA uses Python...
            
              
	      ... joining users such as Rackspace,
	      Industrial Light and Magic,
	      AstraZeneca,
	      Honeywell,
	      and many others.
          

          
	    
	      
	      What they are saying...
	      
                ITA Software:
                Historically, [Python] is not known for being something that somebody
would go out and code enterprise software in.  [However,] it's definitely an enterprise-caliber language in terms of stability, scalability [and] the ability to have a large number of people work together on a project.
-- Dan Kelley, director of application integration at ITA Software,
quoted in eWeek.
              
	      more...      
	    

	  
	    Using Python For...
	    
		Web Programming
		  
		    CGI, 
		    Zope, 
		    Django, 
		    TurboGears, 
		  
		  XML
		  
		Databases
		  
		    ODBC, 
		  
		  MySQL
		  
		GUI Development
		  
		    wxPython, 
		    tkInter, 
		    PyGtk, 
		  
		  PyQt
		  
		Scientific and Numeric
		  
		  
		  Physics
		  
		Education
		  
		    pyBiblio, 
		  
		  Software Carpentry Course
		  
		Networking
		  
		    Sockets, 
		  
		  Twisted
		  
		Software Development
		  
		    Buildbot, 
		    Trac, 
		    Roundup, 
		  
		  IDEs
		  
		Game Development
		  
		    PyGame, 
		  
		  3D Rendering
		  
	    
	    more...      
	  
	

        
          



        





Python is a programming language that lets you work more quickly and
integrate your systems more effectively. You can learn to use Python
and see almost immediate gains in productivity and lower maintenance
costs.
Python runs on Windows, Linux/Unix, Mac OS X, and has been ported to
the Java and .NET virtual machines.
Python is free to use, even for commercial products, because of its
OSI-approved open source license.
New to Python or choosing between Python 2 and Python 3? Read Python 2 or
Python 3.
The Python Software Foundation holds the intellectual property
rights behind Python, underwrites the PyCon conference, and funds many other projects in the Python community.
Read more, -or- download Python now



        

        
            
	      
		Python 3.3.3 release candidate 2 has been released
		  




The second release candidate for Python 3.3.3 has been released.
		Published: Tue, 12 October 2013, 08:00 +0100
		Python 2.7.6 released
		  




Python 2.7.6 is now available.
		Published: Sun, 10 November 2013, 02:30 -0500
		Python 2.6.9 final available
		  




The final release of Python 2.6.9 (and the final release of the 2.6 series) is now available.
		Published: Tue, 29 October 2013, 12:30 -0400
		Python 2.7.6 release candidate 1 available
		  




A release candidate of Python 2.7.6 has been released.
		Published: Sun, 27 October 2013, 15:00 -0400
		Python 3.3.3 release candidate 1 has been released
		  




The release candidate for Python 3.3.3 has been released.
		Published: Sun, 27 October 2013, 18:00 +0100
		Python 3.4.0 alpha 4 has been released
		  




The fourth and final alpha for Python 3.4, Python 3.4.0a4, has been released.
		Published: Sun, 20 October 2013, 17:30 -0700
		Python 2.6.9 release candidate 1 has been released
		  




The first release candidate for Python 2.6.9, Python 2.6.9rc1, has been released.
		Published: Mon, 30 September 2013, 21:12 -0400
	      [ RSS ]
             
        

      

      
      
	
 	  Website maintained by the Python community
	  hosting by xs4all /
	  design by Tim Parkin
	
	Copyright &copy; 1990-2013, Python Software Foundation
	Legal Statements

17.

In [38]:
# compose_hangul3.py 
# 책 페이지 169
cho_list_eng = [ "r", "R", "s", "e", "E", "f", "a", "q", "Q", "t", "T", "d", "w", "W", "c", "z", "x", "v", "g"]
jung_list_eng = ["k", "o", "I", "O", "j", "p", "u", "P", "h", "hk", "hO", "hl", "y", "n", "nj", "np", "nl", "b", "m", "ml", "l"]
jong_list_eng = ["", "r", "R", "rt", "s", "sw", "sg", "e", "f", "fr", "fa", "fq", "ft", "fx", "fv", "fg", "a", "q", "qt", "t", "T", "d", "w", "C", "z", "x", "v", "g"]

def compose_hangul3(cho_e, jung_e, jong_e=''):
    cho = cho_list_eng.index(cho_e)
    jung = jung_list_eng.index(jung_e)
    jong = jong_list_eng.index(jong_e)
    code = 0xac00 + ((cho*21) + jung)*28 + jong
    return chr(code)

print (compose_hangul3('g', 'k', 's'), compose_hangul3('r', 'm', 'f'))
한 글

In [39]:
def split_into_syllables(s):
    jung_list_eng = 'k o I O j p u P h hk hO hl y n nj np nl b m ml l'.split()
    s2 = s
    pos = 0
    syllable_start = []
    phonemes = []
    while s2:
        n = 0
        if s2[:2] in jung_list_eng:
            n = 2
        elif s2[0] in jung_list_eng:
            n = 1
        if n:   # 모음
            syllable_start.append(len(phonemes)-1)
            phonemes.append(s2[:n])
            jaso = 'v'
            s2 = s2[n:]
            pos += n
        elif s2[0] in ' \t\n':  # 공백
            syllable_start.append(len(phonemes))
            phonemes.append(s2[:1])
            jaso = 'v'
            s2 = s2[1:]
            pos += 1
        else:   # 자음
            phonemes.append(s2[:1])
            jaso = 'c'
            s2 = s2[1:]
            pos += 1
        
    syllable_start.append(len(phonemes))
    return [tuple(phonemes[k1:k2]) for k1, k2 in zip(syllable_start[:-1], syllable_start[1:])]
In [40]:
s = 'tpwhdeodhkd gksrmf'
syllables = split_into_syllables(s)
for syll in syllables:
    try:
        print (compose_hangul3(*syll), end='')
    except:
        for c in syll[0]:
            print(c, end='')
세종대왕 한글
In [40]: