Python。如何从 txt 文件中执行 split() 操作?

 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

从这个文件中我必须 8.4 打开文件 romeo.txt 并逐行读取它。对于每一行,使用 split() 方法将该行拆分为单词列表。该程序应该构建一个单词列表。对于每行上的每个单词,检查该单词是否已在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序排序并打印结果单词。您可以在http://www.py4e.com/code3/romeo.txt下载示例数据


这是框架,所以我应该只遵循这个代码,并使用append()、slpit()和sort()我应该使用它们。或者在其他情况下会显示错误。因为这个作业来自 coursera.com


fname = input("Enter file name: ")

fh = open(fname)

lst = list()

for line in fh:

print(line.rstrip())

输出应如下所示:


      ['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']

将不胜感激。谢谢


子衿沉夜
浏览 167回答 4
4回答

catspeake

words = set()with open('path/to/romeo.txt') as file:    for line in file.readlines():        words.update(set(line.split()))words = sorted(words)

Qyouu

以下应该有效:fname = input("Enter file name: ")with open(fname, 'r') as file:    data = file.read().replace('\n', '')# Split by whitespacearr = data.split(' ')#Filter all empty elements and linebreaksarr = [elem for elem in arr if elem != '' and elem != '\r\n']# Only unique elementsmy_list = list(set(arr))# Print sorted arrayprint(sorted(arr))

拉风的咖菲猫

要读取文本文件,您必须先打开它:with open('text.txt', 'r') as in_txt:    values = in_txt    l=[]    for a in values:        l.extend(a.split())    print(l)用于with确保您的文件已关闭。'r'用于只读模式。 extend将从列表中添加元素,在本例中a添加到现有列表中l。

开满天机

在 python 中使用sets 比示例中的 list 更好。集合是没有重复成员的可迭代对象。# open, read and split wordsmyfile_words = open('romeo.txt').read().split()# create a set to save wordslist_of_words = set()# for loop for each word in word list and it to our word listfor word in myfile_words:    list_of_words.add(word)# close file after use, otherwise it will stay in memorymyfile_words.close()# create a sorted list of our wordslist_of_words = sorted(list(list_of_words))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python