[英]How to split string into words that do not contain whitespaces in python?
[英]Python how to split a string into words that contain words with a single quote?
我有一个字符串a
,我想返回一个列表b
,其中包含b
中的单词不是以@
或#
开头的,并且不包含任何非单词字符。
但是,我很难将“他们”之类的单词保留为一个单词。 请注意,“ Okay .... so”之类的单词应分为两个单词“ okay”和“ so”。
我认为可以通过修改正则表达式来解决问题。 谢谢!
a = "@luke5sos are you awake now?!!! me #hashtag time! is@ over, now okay....so they're rich....and hopefully available?"
a = a.split()
b = []
for word in a:
if word != "" and word[0] != "@" and word[0] != "#":
for item in re.split(r'\W+\'\W|\W+', word):
if item != "":
b.append(item)
else:
continue
else:
continue
print b
将所有这些规则组合成一个正则表达式会更容易:
import re
a = "@luke5sos are you awake now?!!! me #hashtag time! is@ over, now okay....so they're rich....and hopefully available?"
b = re.findall(r"(?<![@#])\b\w+(?:'\w+)?", a)
print(b)
结果:
['are', 'you', 'awake', 'now', 'me', 'time', 'is', 'over', 'now', 'okay', 'so', "they're", 'rich', 'and', 'hopefully', 'available']
正则表达式的工作方式如下:
(?<![@#])
检查以确保它不在#
或@
之后。 \\b
检查它是否在单词的开头。 这很重要,因此@
/ #
检查不仅要跳过一个字符然后继续。 \\w+
匹配一个或多个“单词”类型字符的序列。 (?:'\\w)?
匹配(?:'\\w)?
。 需要注意的是,第四步是写这种方式,使they're
将算作一个字,但只有this
, that
和these
从this, 'that', these
将匹配。
以下代码(a)将....
视为单词分隔符,(b)删除结尾的非单词字符,例如问号和感叹号,(c)拒绝以#
或@
开头的任何单词,否则包含非字母字符:
a = "@luke5sos are you awake now?!!! me #hashtag time! is@ over, now okay....so they're rich....and hopefully available?"
a = a.replace('....', ' ')
a = re.sub('[?!@#$%^&]+( |$)', ' ', a)
result = [w for w in a.split() if w[0] not in '@#' and w.replace("'",'').isalpha()]
print result
这将产生所需的结果:
['are', 'you', 'awake', 'now', 'me', 'time', 'is', 'now', 'okay', 'so', "they're", 'rich', 'and', 'hopefully', 'available']
import re
v = re.findall(r'(?:\s|^)([\w\']+)\b', a)
给出:
['are', 'you', 'awake', 'now', 'me', 'time', 'is', 'over', 'now',
'okay', 'so', "they're", 'rich', 'and', 'hopefully', 'available']
据我了解,您不希望其中包含数字的单词,并且想要忽略除单引号之外的所有其他特殊字符。 您可以尝试这样的事情:
import re
a = re.sub('[^0-9a-zA-Z']+', ' ', a)
b = a.split()
我还无法尝试语法,但希望它应该能工作。 我建议用空格替换所有不是aplha-numberic或单个qoute的字符 。 因此,这将导致一个字符串,其中所需的字符串由多个空格分隔。 只需调用不带参数的split
函数,即可将字符串拆分为单词,同时还要照顾多个空格。 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.