python - 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 关键字是否理解文件中的每个单词在拆分之前都是一个迭代?
解决方案
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)
推荐阅读
- reactjs - 如何在 WordPress Gutenberg(块编辑器)面板中添加和保存我自己的自定义字段?
- python - 在 AWS Lambda 函数上执行 Python 脚本时出现问题
- amazon-quicksight - 如何在 AWS QuickSight 中将周显示为数字?
- java - @RefreshScope 具有不同的 *.properties 文件
- sql - 将 varchar 转换为日期时间 dd/mm/yy 转换为 yyyy-mm-dd
- java - 是否可以在 Akka 演员内部设置不使用事件的计时器?(输入阿卡)
- angular - Angular on refresh getItem undefined for Local storage service
- delphi - 如何在所有者绘制的 ListView 中恢复突出显示功能
- ruby-on-rails - 仅在其所有 has_many 集合都具有特定列的值时查找对象
- android - 颤振错误:每个孩子必须恰好布置一次。点击手势检测器