【问题标题】:How to split each words from several lines of a word file? (python)如何从单词文件的几行中拆分每个单词? (Python)
【发布时间】:2020-11-08 23:29:06
【问题描述】:

我有一个文本文件:

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

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

期望的输出:

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

我被困在这里:

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) 

【问题讨论】:

  • line.split() 将被您可能删除的空格分隔。
  • 那我应该怎么把它分成单词呢?
  • 为什么“in”在“lives”之前?
  • 字母顺序 ig.
  • * 'He' 将出现在 'I' 之前。

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


【解决方案1】:

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

【讨论】:

  • 对不起。它不起作用。我不想重复重复的话。例如:如果我在文件中有 3 个“生命”,我希望输出只显示一个“生命”。
  • 然后在最后一步使用 x = set(lst) 输出所需的标准。
  • 您可以使用 set 操作删除列表中的重复项。
  • 编辑了我的帖子。请立即检查。
【解决方案2】:

我了解您想要实现的目标。这里有一个更简单的方法,而不是您编写它的方式:

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

对其进行了测试以确保其有效:

编辑:

我稍微修改了您的代码以满足您的用例。

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

希望能解决您的问题。

【讨论】:

  • 感谢您的努力。但是我的老师特别要求这种方法。
  • @RifatAbdurRahman 我通过修改您的代码添加了备用代码,请查看。
  • 工作就像一个魅力。谢谢!
【解决方案3】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 2020-07-24
    • 1970-01-01
    • 2013-04-20
    相关资源
    最近更新 更多