Python正则表达式将字符串转换为单词列表(包括带连字符的单词)

3
我想解析一个字符串以获取包括所有单词(连字符单词也包括在内)的列表。当前的代码如下:
s = '-this is. A - sentence;one-word'
re.compile("\W+",re.UNICODE).split(s)

返回:

['', 'this', 'is', 'A', 'sentence', 'one', 'word']

and I would like it to return:

['', 'this', 'is', 'A', 'sentence', 'one-word']
5个回答

4

如果您不需要空字符串,可以使用模式 \w(?:[-\w]*\w)? 进行匹配:

>>> import re
>>> s = '-this is. A - sentence;one-word'
>>> rx = re.compile(r'\w(?:[-\w]*\w)?')
>>> rx.findall(s)
['this', 'is', 'A', 'sentence', 'one-word']

请注意,它不会匹配带有撇号的单词,例如won't

2

在这里,我提供一个传统的“为什么要使用正则表达式语言,而不是使用Python”的替代方案:

import string
s = "-this is. A - sentence;one-word what's"
s = filter(None,[word.strip(string.punctuation)
                 for word in s.replace(';','; ').split()
                 ])
print s
""" Output:
['this', 'is', 'A', 'sentence', 'one-word', "what's"]
"""

1
你可以使用"[^\w-]+"代替。

这将返回-this,但我也不知道更好的解决方案。我感觉除了再次检查结果以删除不需要的负号之外,没有其他方法了。 - Aaron Digulla

1

s = "-this is. A - sentence;one-word what's"
re.findall("\w+-\w+|[\w']+",s)

结果: ['this', 'is', 'A', 'sentence', 'one-word', "what's"]

请注意,正确的顺序是先查找连字符单词!


0
你可以尝试使用NLTK库:
>>> import nltk
>>> s = '-this is a - sentence;one-word'
>>> hyphen = r'(\w+\-\s?\w+)'
>>> wordr = r'(\w+)'
>>> r = "|".join([ hyphen, wordr])
>>> tokens = nltk.tokenize.regexp_tokenize(s,r)
>>> print tokens
['this', 'is', 'a', 'sentence', 'one-word']

我在这里找到了它:http://www.cs.oberlin.edu/~jdonalds/333/lecture03.html 希望能有所帮助


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接