【问题标题】:Python convert list of multiple words to single wordsPython将多个单词列表转换为单个单词
【发布时间】:2015-05-07 04:26:24
【问题描述】:

我有一个单词列表,例如:

words = ['one','two','three four','five','six seven']# 引号丢失

我正在尝试创建一个新列表,其中列表中的每个项目都只是一个单词,所以我会:

words = ['one','two','three','four','five','six','seven']

最好的办法是将整个列表加入一个字符串,然后对字符串进行标记?像这样的:

word_string = ' '.join(words) tokenize_list = nltk.tokenize(word_string)

或者有更好的选择吗?

【问题讨论】:

  • ' '.join(words).split(' ') 有什么问题吗?
  • @EdChum 我认为这是一个很好的答案
  • 我能想到的唯一其他解决方案是分别标记每个项目并加入结果。我认为您的解决方案更好。

标签: python nlp nltk


【解决方案1】:
words = ['one','two','three four','five','six seven']

有一个循环:

words_result = []
for item in words:
    for word in item.split():
        words_result.append(word)

或作为一种理解:

words = [word for item in words for word in item.split()]

【讨论】:

  • 您说得很好:在我的版本中,word 可能实际上不是一个词。我会改的。
【解决方案2】:

您可以使用空格分隔符加入,然后再次拆分:

In [22]:

words = ['one','two','three four','five','six seven']
' '.join(words).split()
Out[22]:
['one', 'two', 'three', 'four', 'five', 'six', 'seven']

【讨论】:

  • 这看起来很棒,很好的解决方案!
  • 小建议:你可以不带参数地调用split() 来保存三个字符。
  • @TigerhawkT3 嗯。我以为我确实尝试过,但它失败了,但它确实有效,会更新谢谢
【解决方案3】:

这里有一个稍微使用正则表达式的解决方案:

import re

words = ['one','two','three four','five','six seven']
result = re.findall(r'[a-zA-Z]+', str(words))

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 2017-08-08
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2015-06-02
    • 2019-12-02
    相关资源
    最近更新 更多