如何从单词文件的几行中拆分每个单词? (蟒蛇)

时间:2020-07-19 16:45:52

标签: python python-3.x string list file

我有一个文本文件:

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

说明:打开文件并逐行读取。对于每一行,使用split()方法将该行拆分为单词列表。该程序应建立单词列表。对于每一行中的每个单词,请检查该单词是否已在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序对结果单词进行排序和打印。

所需的输出:

fname = input("Enter file name: ") 
fh = open(fname)
lst = list()
for line in fh:
    line=line.rstrip()
    lst = line.split()
    lst.append(line)
    lst.sort()
print(lst) 

我被困在这里:

List("method1","method2","method3")

3 个答案:

答案 0 :(得分:2)

line.split()为您提供一个列表,该列表将作为列表对象添加到您的第一个列表中。因此,不要使用lst.append(line)来使用lst.extend(line)来获得正确的输出。

答案 1 :(得分:1)

我了解您要达到的目标。除了编写方式以外,这里还有一个更简单的方法:

import re
ls=set(re.findall(r"[\w']+", text)) #text is the input
print(sorted(ls))

对其进行了测试以确保其正常工作: Sample python program for set and sort

编辑:

我对您的代码做了一些修改以满足您的用例。

fh = open(raw_input("Enter file name: "),'r')
lst = list()
for line in fh:
    words = line[:-1].split(" ")
    for word in words:
        if word not in lst:
            lst.append(word)
print(sorted(lst))

输出:

Enter file name: file.txt
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grie', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

希望能解决您的问题。

答案 2 :(得分:0)

output = []
with open('file_name') as f:
    for i in f.readlines():
        for j in words_to_split:
            i = ''.join(i.split(j))
        output.append(i)