【问题标题】:python extract word from multiple lines into 1 listpython从多行中提取单词到1个列表中
【发布时间】:2016-07-11 22:44:55
【问题描述】:

我正在尝试将以下文本中的唯一单词提取到 1 个列表中。

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

但我不断在列表中为每一行文本获取一个列表。我知道我有一些“\n”要摆脱,但不知道如何摆脱。

这是我的代码:

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

我得到的输出:

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

谢谢!!

【问题讨论】:

  • for word in line: word =line.lower().split() 。这里没有word in line 的用处,因为您在它的正下方重新分配了word。相反:for word in line.split(): lst.append(word) 可能更接近你想要的。
  • 感谢大家的帮助,这些都非常有帮助。而且比我想出的解决方案干净得多:使用count = count + 1 循环和word[count]。

标签: python list split strip


【解决方案1】:

当您执行line.lower.split() 时,您会得到一个单词列表。您正在将单词列表附加到列表中,lst。使用扩展而不是附加。 Extend 将添加 split() 函数返回的列表的每个元素。第二个 for 循环 for word in line: 也是不必要的。 此外,如果您想提取唯一的单词,您可能需要查看 set 数据类型。

【讨论】:

    【解决方案2】:

    使用这个:

    list += word
    

    代替:

    lst.append(word)
    

    【讨论】:

    • Append 将列表添加到列表,但 + 将它们组合在一起。
    • .extend 可能会更明确。也适用于非列表迭代。
    【解决方案3】:

    正如@Shalan 和@BladeMight 所建议的,问题在于word = line.lower().split() 生成了一个列表,而append 附加了该列表而不是添加到它。我认为写这个的语法简单的方法是:

    fname = input("Enter file name: ")
    fh = open(fname)
    lst = list()
    for line in fh:
        line = line.rstrip("\n")
    lst += line.lower().split()
    

    【讨论】:

      【解决方案4】:

      如果顺序不重要,可以用set代替list:

      fname = input("Enter file name: ")
      fh = open(fname)
      uniq_words = set()
      for line in fh:
          line = line.strip()
          uniq_words_in_line = line.split(' ')
          uniq_words.update(uniq_words_in_line)
      print(uniq_words)
      

      【讨论】:

      • 您可能希望使用.update 进行就地联合,而不是每一步都重新创建一个新集合。
      • @TadhgMcDonald-Jensen,好建议,我刚刚更新了我的答案。
      • 更新需要任何可迭代的,不需要集合调用。
      【解决方案5】:

      列表推导与您所做的一样。

      然后使用chain.from_iterable将所有子列表链接到一个列表中:

      from itertools import chain
      
      lst = list(chain.from_iterable(line.lower().split() for line in f))
      

      【讨论】:

      • OP 不想要嵌套列表,他们试图仅获取字符串的结果,而不是字符串的子列表。
      • @TadhgMcDonald-Jensen 我误读了 OP 的问题。谢谢你
      • 请使用chain.from_iterable 而不是chain(*[..])。
      • @TadhgMcDonald-Jensen 感谢您的关注
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      相关资源
      最近更新 更多