我一直在编写程序,从.txt文件中读取4个句子,并将所有单词添加到一个新的空列表中。
我的代码如下:
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
words.sort()
if words not in lst:
lst.append(words)
print lst我得到了以下结果:
[“但是”、“休息”、“光”、“软”、“透过”、“什么”、“窗户”、“那边”][“但是”、“断裂”、“光”、“软”、“穿过”、“什么”、“窗户”、“那边”、“它”、“朱丽叶”、“和”、“东方”、“是”、“太阳”、“太阳”、“那”,“但是”,“但”,“休息”,“光”,“软”,“透过”,“什么”,“窗户”,“那边”,“它”,“朱丽叶”,“和”,“东方”,“是”,“是”,“太阳”,“”,“起来”,“和”,“嫉妒”,“美丽”,“杀戮”,“月亮”,“太阳”,“但是”,“但”,“休息”,“光”,“软”,“透过”,“什么”,“窗户”,“那边”,“它”,“朱丽叶”,“和”,“东方”,“是”,“是”,“太阳”,“”,“起来”,“和”,“嫉妒”,“美丽”,“杀戮”,“月亮”,“太阳”,‘'the','Who',’已经‘,’‘和’‘,’悲伤‘,'is',’苍白‘,’病‘,’with‘
我能做些什么来获得以下信息:
“爱”、“但是”、“它”、“朱丽叶”、“谁”、“已经”、“休息”、“东方”、“嫉妒”、“公平”、“悲伤”、“是”、“杀”、“光”、“月亮”、“苍白”、“病了”、“软”、“太阳”、“透过”、“什么”、“窗户”、“与”、“yonder”
句子是:但是柔和的光从那边的窗户打破,是东方和朱丽叶是太阳,升起美丽的太阳,杀死嫉妒的月亮,谁已经生病和苍白的悲伤。
发布于 2016-11-04 17:45:16
您正在使用line.split()正确地将每一行拆分成一个单词列表,但是您没有迭代刚才创建的名为words的新列表。相反,您将列表words作为对象与lst的内容进行比较,然后将words作为对象附加到lst。这将导致lst成为列表列表,正如您在收到的结果中所显示的那样。
为了实现您要寻找的单词数组,您必须遍历words并单独添加每个单词,只要它不在lst中
for word in words:
if word not in lst:
lst.append(word)编辑:找到了关于同一个问题的另一个问题/答案 --可能是同一个类的分配。
发布于 2016-11-04 17:39:55
您希望使用一组将唯一列出元素的集合:
my_string = "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"
lst = set(my_string.split(' '))这会给你你想要的。您可以在字符串、列表等上使用set,python 3.5中的集合
发布于 2016-11-04 17:39:30
最简单的方法是使用一个集合,并附加每个单词。
file_name = raw_input("Enter file name: ")
with open(file_name, 'r') as fh:
all_words = set()
for line in fh:
line = line.rstrip()
words = line.split()
for word in words:
all_words.add(word)
print(all_words)https://stackoverflow.com/questions/40428590
复制相似问题