【发布时间】:2018-09-16 17:53:12
【问题描述】:
代码:
import re
def main():
a=['the mississippi is well worth reading about', ' it is not a commonplace river, but on the contrary is in all ways remarkable']
b=word_find(a)
print(b)
def word_find(sentence_list):
word_list=[]
word_reg=re.compile(r"[\(|\)|,|\'|\"|:|\[|\]|\{|\}| |\-\-+|\t|;]?(.+?)[\(|\)|,|\'|\"|:|\[|\]|\{|\}| |\-\-+|\t|;]")
for i in range(len(sentence_list)):
words=re.findall(word_reg,sentence_list[i])
word_list.append(words)
return word_list
main()
我需要将每个单词分解为列表的单个元素
现在输出如下所示:
[['the', 'mississippi', 'is', 'well', 'worth', 'reading'], ['it', 'is', 'not', 'a', 'commonplace', 'river', 'but', 'on', 'the', 'contrary', 'is', 'in', 'all', 'ways']]
发现第一句'about'和第二句'remarkable'的最后一个字不见了
我的正则表达式可能有问题
word_reg=re.compile(r"[\(|\)|,|\'|\"|:|\[|\]|\{|\}| |\-\-+|\t|;]?(.+?)[\(|\)|,|\'|\"|:|\[|\]|\{|\}| |\-\-+|\t|;]")
但是如果我像这样在这个正则表达式的最后部分添加一个问号:
[\(|\)|,|\'|\"|:|\[|\]|\{|\}| |\-\-+|\t|;]**?**")
结果变成许多单个字母而不是单词。我能用它做什么?
编辑:
我没有使用 string.split 的原因是人们可能有很多断词的方法
例如:当人们输入a--b时,没有空格,但我们必须将其分解为'a','b'
【问题讨论】:
-
你有什么理由不想像
string.split(' ')那样在空格上分割字符串? -
我编辑了这个问题来解释为什么不是 string.split(" ")