- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
所以,我正在为 Coursera 上的作业编写程序,我解决了它,但出现了一些意外行为。以下代码以 romeo.txt 为输入:
fname = input("Enter file name: ")
fh = open(fname, 'r')
lst = list()
words = ''
fin = list()
for line in fh:
words += line.strip(' ')
words = words.replace('\n', ' ')
for line in words:
lst += words.split(' ')
print(lst)
它没有给我一个只出现一次的单词列表,而是给了我每个单词,但重复了未知次数。
Gives me a huge list
of repeating words: ['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', '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', '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', 'But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks', 'It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun', 'Arise', 'fair', 'sun' . . . .,
单词重复的次数远不止于此。
最佳答案
最初你说:
words = ''
好的。所以 words
是一个字符串。然后,你说:
for line in fh:
words += line.strip(' ')
对于文件中的每一行,从当前行去除空格并将其附加到words
。您要附加到 words
字符串的每次迭代。循环完成后,words
将是一个巨大的字符串。
然后,你说:
words = words.replace('\n', ' ')
好的。 words
仍然是一个字符串。您所做的只是将所有换行符替换为空格。
然后,你说:
for line in words:
lst += words.split(' ')
line
在这种情况下,不是这个临时变量的好名称,因为您不再迭代这些行。您的可迭代对象是 words
,它是一个字符串。当你遍历一个字符串时,你得到的是单个字符,而不是行:
>>> for line in "abcdefg":
print(line)
a
b
c
d
e
f
g
>>>
只是因为我正在调用临时变量 line
,并不意味着它实际上就是这样。我可以给它起任何名字,但我仍然会收到相同的输出。因此,此变量的更好名称是 char
,例如。
回到您的代码片段,因为您正在遍历 words
字符串中的字符,所以您正在使用 words.split( ' ')
,每个字符一次!我不需要查看您的输入文件就知道这是一个巨大的列表。 lst
列表中的字符串数大约等于文件中的单词数乘以文件中的字符数。
关于python - python中列表的本质,为什么我得到一个重复列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58845796/
我了解了 NodeJS 的非阻塞特性,以及 I/O 操作如何实现非阻塞。我创建了一个简单的测试来证明这一点 var request = require('request'); var http = r
我是一名优秀的程序员,十分优秀!