习题8.1 编写chop函数,移除列表的头元素和尾元素,并返回None值;然后编写middle函数,移除列表的头元素和尾元素
def chop(phrase):
length = len(phrase)
phrase = phrase[1:length-1]
#t = phrase[0]
#m = phrase[length-1]
#phrase.remove(t)
#phrase.remove(m)
def middle(phrase):
length = len(phrase)
phrase = phrase[1:length-1]
return phrase
words1 = ['a', 'b', 'c', 'd', 'e']
words2 = ['m', 'n', 'p', 'q', 's']
print 'chop is:', chop(words1)
print 'middle is:', middle(words2)
习题8.4 编写一个程序,打开romeo.txt文件,按行读取,对每一行使用split函数,将其分解成一系列的单词列表,对于每一个单词,检查它是否已经存在于列表之中,若单词未出现在列表中,把它添加进来
fname = raw_input('Please enter a file name: ')
try:
fhand = open(fname)
except:
print 'Please enter!'
count = 0
empty = []
for line in fhand:
words = line.split()
if len(words) == 0:
continue
for word in words:
i = 0
if empty.__contains__(word):
continue
else:
empty.append(word)
# if len(empty) == 0:
# empty.append(word)
# count=0
# for word2 in empty :
# if empty[count] == word:
# break
# if count== (len(empty)-1) :
# empty.append(word)
# count=count+1
print empty