将字符串拆分为单词和标点符号
- 2025-03-05 09:15:00
- admin 原创
- 32
问题描述:
我正在尝试将字符串拆分成单词和标点符号,并将标点符号添加到拆分生成的列表中。
例如:
>>> c = "help, me"
>>> print c.split()
['help,', 'me']
我真正想要的列表是这样的:
['help', ',', 'me']
所以,我希望将字符串在空格处分割,并将标点符号与单词分割开。
我尝试先解析字符串,然后运行拆分:
>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
这产生了我想要的结果,但是对于大文件来说速度非常慢。
有没有办法更有效地做到这一点?
解决方案 1:
这或多或少是这样做的方法:
>>> import re
>>> re.findall(r"[w']+|[.,!?;]", "Hello, I'm a string!")
['Hello', ',', "I'm", 'a', 'string', '!']
诀窍在于,不要考虑在哪里分割字符串,而是考虑在标记中包含什么。
注意事项:
下划线 (_) 被视为单词内部字符。如果您不想这样,请替换 \w。
这对于字符串中的(单)引号不起作用。
将您想要使用的任何其他标点符号放在正则表达式的右半部分。
其中未明确提及的任何内容都会被默默删除。
解决方案 2:
这是一个支持 Unicode 的版本:
re.findall(r"w+|[^ws]", text, re.UNICODE)
第一个替代方案捕获单词字符序列(由unicode定义,因此“résumé”不会变成['r', 'sum']
);第二个替代方案捕获单个非单词字符,忽略空格。
请注意,与最佳答案不同,这将单引号视为单独的标点符号(例如 "I'm" -> ['I', "'", 'm']
)。这似乎是 NLP 中的标准,所以我认为它是一个功能。
解决方案 3:
如果您要使用英语(或其他一些常用语言)工作,您可以使用NLTK(还有许多其他工具可以做到这一点,例如FreeLing)。
import nltk
nltk.download('punkt')
sentence = "help, me"
nltk.word_tokenize(sentence)
解决方案 4:
这是我的参赛作品。
我怀疑这在效率方面能否保持良好,或者它是否能涵盖所有情况(请注意“!!!”组合在一起;这可能是也可能不是一件好事)。
>>> import re
>>> import string
>>> s = "Helo, my name is Joe! and i live!!! in a button; factory:"
>>> l = [item for item in map(string.strip, re.split("(W+)", s)) if len(item) > 0]
>>> l
['Helo', ',', 'my', 'name', 'is', 'Joe', '!', 'and', 'i', 'live', '!!!', 'in', 'a', 'button', ';', 'factory', ':']
>>>
如果您要逐行执行此操作,一个明显的优化就是预先编译正则表达式(使用 re.compile)。
解决方案 5:
这对我有用
import re
i = 'Sandra went to the hallway.!!'
l = re.split('(W+?)', i)
print(l)
empty = ['', ' ']
l = [el for el in l if el not in empty]
print(l)
Output:
['Sandra', ' ', 'went', ' ', 'to', ' ', 'the', ' ', 'hallway', '.', '', '!', '', '!', '']
['Sandra', 'went', 'to', 'the', 'hallway', '.', '!', '!']
解决方案 6:
这是对您的实现的一个小更新。如果您尝试做任何更详细的事,我建议您查看 le dorfier 建议的 NLTK。
这可能只会快一点,因为使用 ''.join() 代替 +=,而已知后者更快。
import string
d = "Hello, I'm a string!"
result = []
word = ''
for char in d:
if char not in string.whitespace:
if char not in string.ascii_letters + "'":
if word:
result.append(word)
result.append(char)
word = ''
else:
word = ''.join([word,char])
else:
if word:
result.append(word)
word = ''
print result
['Hello', ',', "I'm", 'a', 'string', '!']
解决方案 7:
我想出了一种方法来标记所有单词和W+
模式,不需要硬编码:
>>> import re
>>> sentence = 'Hello, world!'
>>> tokens = [t.strip() for t in re.findall(r'.*?S.*?(?:|$)', sentence)]
['Hello', ',', 'world', '!']
这.*?S.*?
是一个模式,匹配任何非空格的内容,$
如果它是标点符号,则添加以匹配字符串中的最后一个标记。
但请注意以下几点——这将对由多个符号组成的标点符号进行分组:
>>> print [t.strip() for t in re.findall(r'.*?S.*?(?:|$)', '"Oh no", she said')]
['Oh', 'no', '",', 'she', 'said']
当然,你可以使用以下方法查找并拆分此类组:
>>> for token in [t.strip() for t in re.findall(r'.*?S.*?(?:|$)', '"You can", she said')]:
... print re.findall(r'(?:w+|W)', token)
['You']
['can']
['"', ',']
['she']
['said']
解决方案 8:
尝试一下:
string_big = "One of Python's coolest features is the string format operator This operator is unique to strings"
my_list =[]
x = len(string_big)
poistion_ofspace = 0
while poistion_ofspace < x:
for i in range(poistion_ofspace,x):
if string_big[i] == ' ':
break
else:
continue
print string_big[poistion_ofspace:(i+1)]
my_list.append(string_big[poistion_ofspace:(i+1)])
poistion_ofspace = i+1
print my_list
解决方案 9:
如果您不被允许导入任何东西,请使用这个!
word = "Hello,there"
word = word.replace("," , " ," )
word = word.replace("." , " .")
return word.split()