用python拆分句子

2024-10-01 09:40:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着把句子分成单词。在

words = content.lower().split()

这给了我一个单词列表

^{pr2}$

有了这个代码:

def clean_up_list(word_list):
    clean_word_list = []
    for word in word_list:
        symbols = "~!@#$%^&*()_+`{}|\"?><`-=\][';/.,']"
        for i in range(0, len(symbols)):
            word = word.replace(symbols[i], "")
        if len(word) > 0:
            clean_word_list.append(word)

我得到的东西是:

'evening', 'and', 'there', 'was', 'morningthe', 'first', 'day'

如果你在列表中看到“morningthe”这个词,它以前在单词之间有“-”。现在,有没有办法把它们分成两个词,比如"morning","the"??在


Tags: inclean列表forlencontent单词lower
3条回答

试图用regex做这件事会让你发疯

>>> re.findall(r'\w+', "Don't read O'Rourke's books!")
['Don', 't', 'read', 'O', 'Rourke', 's', 'books']

一定要看看nltk包。在

或者,您也可以使用^{}str.alpha()从字符串中提取只包含字母表的单词,如下所示:

>>> from itertools import groupby
>>> sentence = 'evening, and there was morning--the first day.'

>>> [''.join(j) for i, j in groupby(sentence, str.isalpha) if i]
['evening', 'and', 'there', 'was', 'morning', 'the', 'first', 'day']

PS:基于Regex的解决方案更干净。我已经提到这是实现这一目标的一个可能的替代方案。


特定于OP:如果您只想在结果列表中的--上拆分,那么在执行拆分之前,可以先将连字符'-'替换为空格{}。因此,您的代码应该是:

^{pr2}$

其中words将保存所需的值。在

我建议采用基于regex的解决方案:

import re

def to_words(text):
    return re.findall(r'\w+', text)

这将查找所有单词-字母字符组,忽略符号、分隔符和空格。在

^{pr2}$

请注意,如果循环使用单词,那么使用返回生成器对象的re.finditer可能更好,因为您不需要一次存储整个单词列表。在

相关问题 更多 >