欢迎访问宙启技术站
智能推送

使用Python编写的get_text_list()函数获取文本列表的实现方法

发布时间:2023-12-11 07:41:10

下面是一个使用Python编写的get_text_list()函数,用于获取文本列表的实现方法:

import re

def get_text_list(text):
    # 使用正则表达式匹配文本中的所有单词或短语
    pattern = r'\b\w+\b'
    words = re.findall(pattern, text)
    
    # 去除重复的单词或短语,并保持它们的相对顺序
    unique_words = list(dict.fromkeys(words))
    
    return unique_words

上述函数使用re.findall()方法和正则表达式模式 \b\w+\b 来匹配输入文本中的所有单词或短语。它返回一个列表,其中包含了出现在文本中的所有单词或短语。

下面是一个使用get_text_list()函数的例子:

text = "Hello, how are you? I hope you are doing well. How is the weather today?"
word_list = get_text_list(text)
print(word_list)

运行上述代码,输出结果如下:

['Hello', 'how', 'are', 'you', 'I', 'hope', 'doing', 'well', 'How', 'is', 'the', 'weather', 'today']

以上示例中,输入的文本包含了一些单词和标点符号。get_text_list()函数成功地将文本中的所有单词提取出来,并把它们存储到一个列表中,输出了列表的内容。

这个函数可以应用于各种文本处理的场景,例如文本分析、自然语言处理等任务。