【问题标题】:List of strings to list of words字符串列表到单词列表
【发布时间】:2021-01-12 11:01:35
【问题描述】:

因此,我正在尝试找出获取字符串列表并将其转换为单词列表的最佳方法。我还想从字符串中删除所有标点符号。我的思考过程是做到以下几点:

  1. 使用 .join() 方法和列表理解/映射从字符串列表中创建一个大字符串。
  2. 使用字符串翻译方法去除标点符号。
  3. 使用 split 方法将巨大的字符串拆分回一个列表。

这似乎是从字符串列表到单词列表的大量步骤。有没有人有更简洁的方法或可以对我的流程提出建议?最终目标是将字符串列表传递给计数器类以查找最常见的单词。

以下是当前输出和所需输出。

list_of_strings = ['This is string one.', 'This is string two.', 'This is string three.'] # current output
list_of_words = ['This', 'is', 'string', 'one', 'This', 'is', 'string', 'two', 'This', 'is', 'string', 'three'] # desired output

【问题讨论】:

  • 三个非常简单的步骤真的是“大量步骤”吗?这对我来说似乎完全合理。
  • 试试这个:list_of_words = ''.join(s for s in list_of_strings).replace('.', ' ').split()
  • @Harshil 确实会产生所需的结果。我唯一能看到的是唯一被替换的标点符号是“。”绝对是要迭代的东西,感谢您的帮助。
  • 如果问题得到解决,请接受任何正确答案。 @user3727648

标签: python-3.x string list data-science


【解决方案1】:

您可以这样尝试(rstrip 来自. 的字符串而不是strip 并在空格周围分割,加入通过sum 分割后获得的列表):

>>> sum([i.rstrip(".").split(" ") for i in list_of_strings], [])
['This', 'is', 'string', 'one', 'This', 'is', 'string', 'two', 'This', 'is', 'string', 'three']

【讨论】:

    【解决方案2】:

    你可以试试这个。

    list_of_words = [j.strip('.') for i in list_of_strings for j in i.split()]
    

    【讨论】:

      【解决方案3】:

      第一个 for 循环一次提取一行。例如:-

      list_of_strings[0] = 'This is string one';
      

      然后word = line.split(),这里split()通过分隔符=(空格)将行拆分为单词

      第二个 for 循环将所有拆分词追加或添加到 list_of_words 数组。

      list_of_strings = ['This is string one.', 'This is string two.', 'This is string three.']
      list_of_words = list()
      
      for line in list_of_strings:
          word = line.split()
      
          for i in word:
              list_of_words.append(i)
      
      print(list_of_words)
      

      【讨论】:

      • 你可以使用 trim() 删除 '.'或者您可以将索引长度增加到 1 以避免包含最多 '.'
      猜你喜欢
      • 2013-01-21
      • 2018-11-07
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      相关资源
      最近更新 更多