【题解】Assignment 8.4 (Python Data Structures)

Tucao: No lectures on his homework really not a lot, but make good use of search'd always do it = = record main question is this investigation a bit more, feel worthy of note about Kazakhstan 0.0

8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

You can download the sample data at http://www.py4e.com/code3/romeo.txt

File like this:

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

My program is this:

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    for i in line.rstrip().split(' '):
        lst.append(i)
lst = list(set(lst))
lst.sort()
print(lst)

The output is this:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

Checked point / Attention:

1, str.split () returns the list of strings for the divided time boundaries. ( Https://www.runoob.com/python/att-string-split.html ) and therefore the case if the direct lst.append () will result list set list from occurring. So here use for in to do a word is written lst. ( Https://www.cnblogs.com/pizitai/p/6398276.html )

2, there is no re-check the output, so it can come reuse lst = list (set (lst) ). ( Https://www.cnblogs.com/nyist-xsk/p/7473236.html )

3, it is noted lst.sort () is no return value, so to be operated individually line. ( Https://www.runoob.com/python/att-list-sort.html )

Released six original articles · won praise 3 · Views 5643

Guess you like

Origin blog.csdn.net/zjt1027/article/details/104071894