为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

子衿沉夜 2023-06-27 14:04:47
 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.comfname = 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']将不胜感激。谢谢
查看完整描述

4 回答

?
catspeake

TA贡献1111条经验 获得超0个赞

words = set()

with open('path/to/romeo.txt') as file:

    for line in file.readlines():

        words.update(set(line.split()))


words = sorted(words)


查看完整回答
反对 回复 2023-06-27
?
Qyouu

TA贡献1786条经验 获得超11个赞

以下应该有效:


fname = input("Enter file name: ")


with open(fname, 'r') as file:

    data = file.read().replace('\n', '')


# Split by whitespace

arr = data.split(' ')


#Filter all empty elements and linebreaks

arr = [elem for elem in arr if elem != '' and elem != '\r\n']


# Only unique elements

my_list = list(set(arr))


# Print sorted array

print(sorted(arr))


查看完整回答
反对 回复 2023-06-27
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

要读取文本文件,您必须先打开它:


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。


查看完整回答
反对 回复 2023-06-27
?
开满天机

TA贡献1786条经验 获得超12个赞

在 python 中使用sets 比示例中的 list 更好。


集合是没有重复成员的可迭代对象。


# open, read and split words

myfile_words = open('romeo.txt').read().split()


# create a set to save words

list_of_words = set()


# for loop for each word in word list and it to our word list

for word in myfile_words:

    list_of_words.add(word)


# close file after use, otherwise it will stay in memory

myfile_words.close()


# create a sorted list of our words

list_of_words = sorted(list(list_of_words))


查看完整回答
反对 回复 2023-06-27
  • 4 回答
  • 0 关注
  • 116 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信