首页 > 解决方案 > for 关键字是否理解字符串是迭代?

问题描述

问题:“打开文件 romeo.txt 并逐行读取。对于每一行,使用 split() 方法将该行拆分为一个单词列表。程序应该构建一个单词列表。对于每一行的每个单词检查单词是否已经在列表中,如果没有将其附加到列表中。程序完成后,按字母顺序排序并打印结果单词。

代码:

fname = input("Enter file name: ")
fh = open(fname)
hh = list()
for sen in fh:
    sen=sen.split()
    for element in sen:
        if element not in hh:
            hh.append(element)
            hh.sort()        
print(hh) 

我想确保我理解了代码。所以首先我们获取文件名然后打开它,然后我们创建一个空列表,然后我们将字符串拆分为一个列表,然后我们检查 sen 中的元素是否在我们创建的空列表中,然后我们附加它并打印。另外,我在使用 for 关键字时有一个问题,for 关键字是否理解文件中的每个单词在拆分之前都是一个迭代?

标签: pythonlistfor-loop

解决方案


Python str.split() 文档:https ://docs.python.org/3/library/stdtypes.html#str.split

fname = input("Enter file name: ") #-- user enters name of a file
fh = open(fname) #-------------------- open the file
hh = list() #------------------------- create an empty list
for sen in fh: #---------------------- loop through lines in the file
    sen=sen.split() #----------------- split the line into words
    for element in sen: #------------- loop through words in the line
        if element not in hh: #------- if word is not in the list of unique words
            hh.append(element) #------ add the word to the list
            hh.sort() #--------------- organize the list
print(hh) #--------------------------- print the list of unique words

hh将是文件中所有唯一单词的列表。

在 Python 中处理文件的最佳方式是使用上下文管理器。Python 上下文管理器文档:https ://docs.python.org/3/library/contextlib.html

您可能应该使用:

filename = input("Enter file name: ")
unique_words = list()
with open(filename, "r") as file: # 'with' Context Manager
    for line in file:
        line = line.split()
        for word in line:
            if word not in unique_words:
                unique_words.append(word)
                unique_words.sort()
print(unique_words)

推荐阅读