[英]Splitting sentences in Python using regex
我正在尝试从句子中拆分单词,标点符号和数字。 但是,我的代码产生了意外的输出。 我该如何解决?
这是我的输入文本(在文本文件中):
"I 2changed to ask then, said that mildes't of men2,
我的代码输出如下:
['"', 'I', '2', 'changed', 'to', 'ask', 'then', ',', 'said', 'that', "mildes't", 'of', 'men2']
但是,预期的输出是:
['"', 'I', '2', 'changed', 'to', 'ask', 'then', ',', 'said', 'that', "mildes't", 'of', 'men','2']
这是我的代码:
import re
newlist = []
f = open("Inputfile2.txt",'r')
out = f.readlines()
for line in out:
word = line.strip('\n')
f.close()
lst = re.compile(r"\d|\w+[\w']+|\w|[^\w\s]").findall(word)
print(lst)
在正则表达式中,“ \\ w”匹配任何字母数字字符,即[a-zA-Z0-9]。
同样在正则表达式的第一部分中,它应为'\\ d +'以匹配多个数字。
通过将'+'更改为'*',可以将正则表达式'\\ w + [\\ w'] + | \\ w'的第二部分和第三部分合并为单个部分。
import re
with open('Inputfile2.txt', 'r') as f:
for line in f:
word = line.strip('\n')
lst = re.compile(r"\d+|[a-zA-Z]+[a-zA-Z']*|[^\w\s]").findall(word)
print(lst)
这给出:
['"', 'I', '2', 'changed', 'to', 'ask', 'then', ',', 'said', 'that', "mildes't", 'of', 'men', '2', ',']
请注意,您的预期输出不正确。 它缺少一个“,”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.