我目前正在尝试使用 Python 标记一些语言数据,并且很好奇是否有一种有效或内置的方法可以将句子字符串拆分为单独的单词和单独的标点符号。例如:
'Hello, my name is John. What's your name?'
Run Code Online (Sandbox Code Playgroud)
如果我用split()在这句话上,那么我会得到
['Hello,', 'my', 'name', 'is', 'John.', "What's", 'your', 'name?']
Run Code Online (Sandbox Code Playgroud)
我想得到的是:
['Hello', ',', 'my', 'name', 'is', 'John', '.', "What's", 'your', 'name', '?']
Run Code Online (Sandbox Code Playgroud)
我尝试使用诸如搜索字符串、查找标点符号、存储它们的索引、从字符串中删除它们然后拆分字符串并相应地插入标点符号等方法,但这种方法似乎效率太低,尤其是在处理大型语料库时。
有谁知道是否有更有效的方法来做到这一点?
谢谢你。
你可以做一个技巧:
text = "Hello, my name is John. What's your name?"
text = text.replace(",", " , ") # Add an space before and after the comma
text = text.replace(".", " . ") # Add an space before and after the point
text = text.replace(" ", " ") # Remove possible double spaces
mListtext.split(" ") # Generates your list
Run Code Online (Sandbox Code Playgroud)
或者只是这个输入:
mList = input().replace(",", " , ").replace(".", " . ")replace(" ", " ").split(" ")
Run Code Online (Sandbox Code Playgroud)
这是一种方法re.finditer,至少似乎适用于您提供的示例数据:
inp = "Hello, my name is John. What's your name?"
parts = []
for match in re.finditer(r'[^.,?!\s]+|[.,?!]', inp):
parts.append(match.group())
print(parts)
Run Code Online (Sandbox Code Playgroud)
输出:
['Hello', ',', 'my', 'name', 'is', 'John', '.', "What's", 'your', 'name', '?']
Run Code Online (Sandbox Code Playgroud)
这里的想法是匹配以下两种模式之一:
[^.,?!\s]+ which matches any non punctuation, non whitespace character
[.,?!] which matches a single punctuation character
Run Code Online (Sandbox Code Playgroud)
据推测,任何不是空格或标点符号的东西都应该是句子中的匹配单词/术语。
请注意,解决此问题的真正好方法是尝试对标点符号或空格进行正则表达式拆分。但是,re.split不支持零宽度环视的拆分,因此我们被迫尝试re.finditer。