Python将单词附加到文件中的列表 [英] Python append words to a list from file

查看:30
本文介绍了Python将单词附加到文件中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来将文件中的文本读取到一个列表中,然后使用 split 函数将其拆分为一个单词列表.对于每个单词,我需要检查它是否已经在列表中,如果没有,我需要使用 append 函数将其添加到列表中.

I'm writing a program to read text from a file into a list, split it into a list of words using the split function. And for each word, I need to check it if its already in the list, if not I need to add it to the list using the append function.

所需的输出是:

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

我的输出是:

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

我一直在尝试对其进行排序并删除开头和结尾的双方括号[[ & ]]",但我无法这样做.由于某种原因,sort() 函数似乎不起作用.

I have been trying to sort it and remove the double square brackets "[[ & ]]" in the begining and end but I'm not able to do so. And fo some reason the sort() function does not seem to work.

请告诉我哪里出错了.

word_list = []
word_list = [open('romeo.txt').read().split()]
for item in word_list:
    if item in word_list:
        continue
    else:
        word_list.append(item)
word_list.sort()
print word_list

推荐答案

使用两个单独的变量.此外,str.split() 返回一个列表,因此无需将 [] 放在它周围:

Use two separate variables. Also, str.split() returns a list so no need to put [] around it:

word_list = []
word_list2 = open('romeo.txt').read().split()
for item in word_list2:
    if item in word_list:
        continue
    else:
        word_list.append(item)
word_list.sort()
print word_list

目前您正在检查 if item in word_list:,这将始终为真,因为 item 来自 word_list.使 item 从另一个列表中迭代.

At the moment you're checking if item in word_list:, which will always be true because item is from word_list. Make item iterate from another list.

这篇关于Python将单词附加到文件中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆