当前位置:首页 » 《随便一记》 » 正文

第五篇【传奇开心果系列】Python文本和语音相互转换库技术点案例示例:详细解读pyttsx3的`preprocess_text`函数文本预处理。

11 人参与  2024年02月24日 12:36  分类 : 《随便一记》  评论

点击全文阅读


传奇开心果短博文系列

系列短博文目录Python文本和语音相互转换库技术点案例示例系列 短博文目录前言一、pyttsx3的`preprocess_text`函数文本预处理基本用法示例代码二、实现更复杂的文本预处理逻辑示例代码三、去除停用词、词干提取示例代码四、词形还原、拼写纠正示例代码五、实体识别、去除HTML标签示例代码六、去除URL链接、处理缩写词示例代码七、处理特定的符号、处理特定的文本模式示例代码八、归纳总结

系列短博文目录

Python文本和语音相互转换库技术点案例示例系列

短博文目录

前言

在这里插入图片描述
在这里插入图片描述pyttsx3在文本转换语音之前,首先要开展系列步骤的文本预处理工作。
这些预处理步骤可以在使用pyttsx3之前应用于文本,以提高转换结果的质量和可读性。预处理后的文本更干净、准确,可以更好地用于语音转换。pyttsx3主要使用preprocess_text函数开展文本预处理。

一、pyttsx3的preprocess_text函数文本预处理基本用法示例代码

在这里插入图片描述
在这里插入图片描述下面是一个使用pyttsx3库进行文本预处理基本用法的示例代码:

import pyttsx3def preprocess_text(text):    # 移除文本中的特殊字符    processed_text = ''.join(e for e in text if e.isalnum() or e.isspace())        # 将文本转换为小写    processed_text = processed_text.lower()        return processed_text# 创建一个TTS引擎engine = pyttsx3.init()# 设置预处理文本text = "Hello, World! This is a text-to-speech example."# 预处理文本processed_text = preprocess_text(text)# 使用TTS引擎朗读预处理后的文本engine.say(processed_text)engine.runAndWait()

在上面的示例代码中,preprocess_text函数用于对文本进行预处理。它首先移除文本中的特殊字符,然后将文本转换为小写。这样可以确保文本在朗读之前被正确处理。

然后,我们使用pyttsx3.init()方法初始化一个TTS引擎。接下来,我们设置要朗读的文本,并将其传递给preprocess_text函数进行预处理。最后,使用engine.say()方法将预处理后的文本传递给TTS引擎进行朗读,然后使用engine.runAndWait()方法等待朗读完成。

你可以根据自己的需求修改preprocess_text函数,以实现更复杂的文本预处理逻辑。

二、实现更复杂的文本预处理逻辑示例代码

在这里插入图片描述在这里插入图片描述
下面是一个修改后的preprocess_text函数,实现了更复杂的文本预处理逻辑:

import redef preprocess_text(text):    # 移除文本中的特殊字符和标点符号    processed_text = re.sub(r'[^\w\s]', '', text)        # 将文本转换为小写    processed_text = processed_text.lower()        # 移除多余的空格    processed_text = re.sub(r'\s+', ' ', processed_text)        return processed_text

在这个修改后的函数中,我们使用了re模块的正则表达式功能。首先,我们使用re.sub()函数和正则表达式[^\w\s]来移除文本中的特殊字符和标点符号。这个正则表达式表示匹配除了字母、数字、下划线和空格之外的任何字符。然后,我们将文本转换为小写,并使用re.sub()函数和正则表达式\s+来移除多余的空格,将连续的多个空格替换为一个空格。

这样,预处理后的文本将只包含小写字母、数字、下划线和单个空格,没有特殊字符和多余的空格。你可以根据自己的需求进一步修改这个函数,添加其他的预处理步骤,例如去除停用词、词干提取等。

三、去除停用词、词干提取示例代码

在这里插入图片描述
在这里插入图片描述当涉及到去除停用词和词干提取时,可以使用一些自然语言处理库,如nltk(Natural Language Toolkit)来实现。下面是一个修改后的preprocess_text函数,包括去除停用词和词干提取的示例代码:

import reimport nltkfrom nltk.corpus import stopwordsfrom nltk.stem import PorterStemmerdef preprocess_text(text):    # 移除文本中的特殊字符和标点符号    processed_text = re.sub(r'[^\w\s]', '', text)        # 将文本转换为小写    processed_text = processed_text.lower()        # 移除多余的空格    processed_text = re.sub(r'\s+', ' ', processed_text)        # 去除停用词    stop_words = set(stopwords.words('english'))    processed_text = ' '.join(word for word in processed_text.split() if word not in stop_words)        # 词干提取    stemmer = PorterStemmer()    processed_text = ' '.join(stemmer.stem(word) for word in processed_text.split())        return processed_text

在这个修改后的函数中,我们首先导入了nltk库,并从nltk.corpus模块导入了停用词和从nltk.stem模块导入了词干提取器PorterStemmer

然后,在preprocess_text函数中,我们创建了一个停用词集合stop_words,使用set(stopwords.words('english'))加载英文停用词。接下来,我们使用列表推导式和条件判断语句,将不在停用词集合中的单词保留下来,形成一个经过去除停用词的文本。

最后,我们创建了一个词干提取器stemmer,使用PorterStemmer()初始化。然后,使用列表推导式和词干提取器将文本中的每个单词提取出词干,并重新组合成一个经过词干提取的文本。

这样,预处理后的文本将不包含停用词,并且每个单词都被提取为其词干形式。你可以根据自己的需求进一步修改这个函数,添加其他的预处理步骤,如词形还原、拼写纠正等。

四、词形还原、拼写纠正示例代码

在这里插入图片描述
在这里插入图片描述要进行词形还原和拼写纠正,我们可以使用nltk库中的WordNetLemmatizerspell模块。下面是一个修改后的preprocess_text函数,包括词形还原和拼写纠正的示例代码:

import reimport nltkfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import word_tokenizefrom nltk import pos_tagfrom nltk import downloadfrom spellchecker import SpellCheckerdef preprocess_text(text):    # 移除文本中的特殊字符和标点符号    processed_text = re.sub(r'[^\w\s]', '', text)        # 将文本转换为小写    processed_text = processed_text.lower()        # 移除多余的空格    processed_text = re.sub(r'\s+', ' ', processed_text)        # 去除停用词    stop_words = set(stopwords.words('english'))    processed_text = ' '.join(word for word in processed_text.split() if word not in stop_words)        # 词形还原    download('averaged_perceptron_tagger')    download('wordnet')    lemmatizer = WordNetLemmatizer()    tokens = word_tokenize(processed_text)    tagged_tokens = pos_tag(tokens)    processed_text = ' '.join(lemmatizer.lemmatize(word, tag) for word, tag in tagged_tokens)        # 拼写纠正    spell = SpellChecker()    processed_text = ' '.join(spell.correction(word) for word in processed_text.split())        return processed_text

在这个修改后的函数中,我们首先导入了nltk库的WordNetLemmatizerword_tokenizepos_tag模块,以及spellchecker库的SpellChecker模块。

然后,在preprocess_text函数中,我们下载了nltk库的averaged_perceptron_taggerwordnet资源,用于词形还原。

接下来,我们创建了一个词形还原器lemmatizer,使用WordNetLemmatizer()初始化。然后,我们使用word_tokenize函数将文本分词为单词列表,使用pos_tag函数为每个单词标记词性,然后使用列表推导式和词形还原器将每个单词还原为其原始形式,最后重新组合成一个经过词形还原的文本。

最后,我们创建了一个拼写纠正器spell,使用SpellChecker()初始化。然后,使用列表推导式和拼写纠正器对文本中的每个单词进行拼写纠正,并重新组合成一个经过拼写纠正的文本。

这样,预处理后的文本将进行词形还原和拼写纠正,以提高文本的质量和准确性。你可以根据自己的需求进一步修改这个函数,添加其他的预处理步骤,如实体识别、去除HTML标签等。

五、实体识别、去除HTML标签示例代码

在这里插入图片描述要进行实体识别和去除HTML标签,我们可以使用nltk库中的ne_chunkBeautifulSoup模块。下面是一个修改后的preprocess_text函数,包括实体识别和去除HTML标签的示例代码:

import reimport nltkfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import word_tokenizefrom nltk import pos_tagfrom nltk import ne_chunkfrom nltk import downloadfrom spellchecker import SpellCheckerfrom bs4 import BeautifulSoupdef preprocess_text(text):    # 去除HTML标签    processed_text = BeautifulSoup(text, "html.parser").get_text()        # 移除文本中的特殊字符和标点符号    processed_text = re.sub(r'[^\w\s]', '', processed_text)        # 将文本转换为小写    processed_text = processed_text.lower()        # 移除多余的空格    processed_text = re.sub(r'\s+', ' ', processed_text)        # 去除停用词    stop_words = set(stopwords.words('english'))    processed_text = ' '.join(word for word in processed_text.split() if word not in stop_words)        # 词形还原    download('averaged_perceptron_tagger')    download('wordnet')    lemmatizer = WordNetLemmatizer()    tokens = word_tokenize(processed_text)    tagged_tokens = pos_tag(tokens)    processed_text = ' '.join(lemmatizer.lemmatize(word, tag) for word, tag in tagged_tokens)        # 拼写纠正    spell = SpellChecker()    processed_text = ' '.join(spell.correction(word) for word in processed_text.split())        # 实体识别    tagged_tokens = pos_tag(word_tokenize(processed_text))    processed_text = ' '.join(chunk.label() if hasattr(chunk, 'label') else chunk[0] for chunk in ne_chunk(tagged_tokens))        return processed_text

在这个修改后的函数中,我们首先导入了nltk库的ne_chunk模块,以及BeautifulSoup模块来处理HTML标签。

然后,在preprocess_text函数中,我们使用BeautifulSoup模块的BeautifulSoup(text, "html.parser").get_text()方法去除文本中的HTML标签。

接下来,我们继续之前的步骤,包括移除特殊字符和标点符号、转换为小写、移除多余的空格、去除停用词、词形还原和拼写纠正。

最后,我们使用pos_tag函数将文本中的单词标记词性,然后使用ne_chunk函数进行实体识别。我们使用列表推导式和条件判断语句,将识别出的实体标签保留下来,形成一个经过实体识别的文本。

这样,预处理后的文本将进行实体识别和去除HTML标签,以进一步提高文本的质量和准确性。你可以根据自己的需求进一步修改这个函数,添加其他的预处理步骤,如去除URL链接、处理缩写词等。

六、去除URL链接、处理缩写词示例代码

在这里插入图片描述要去除URL链接和处理缩写词,我们可以使用正则表达式来匹配和替换文本中的URL链接,以及使用一个缩写词词典来进行缩写词的替换。下面是一个修改后的preprocess_text函数,包括去除URL链接和处理缩写词的示例代码:

import reimport nltkfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import word_tokenizefrom nltk import pos_tagfrom nltk import ne_chunkfrom nltk import downloadfrom spellchecker import SpellCheckerfrom bs4 import BeautifulSoupdef preprocess_text(text):    # 去除HTML标签    processed_text = BeautifulSoup(text, "html.parser").get_text()        # 去除URL链接    processed_text = re.sub(r'http\S+|www.\S+', '', processed_text)        # 移除文本中的特殊字符和标点符号    processed_text = re.sub(r'[^\w\s]', '', processed_text)        # 将文本转换为小写    processed_text = processed_text.lower()        # 移除多余的空格    processed_text = re.sub(r'\s+', ' ', processed_text)        # 去除停用词    stop_words = set(stopwords.words('english'))    processed_text = ' '.join(word for word in processed_text.split() if word not in stop_words)        # 处理缩写词    abbreviations = {        "can't": "cannot",        "won't": "will not",        "it's": "it is",        # 添加其他缩写词和对应的替换    }    processed_text = ' '.join(abbreviations.get(word, word) for word in processed_text.split())        # 词形还原    download('averaged_perceptron_tagger')    download('wordnet')    lemmatizer = WordNetLemmatizer()    tokens = word_tokenize(processed_text)    tagged_tokens = pos_tag(tokens)    processed_text = ' '.join(lemmatizer.lemmatize(word, tag) for word, tag in tagged_tokens)        # 拼写纠正    spell = SpellChecker()    processed_text = ' '.join(spell.correction(word) for word in processed_text.split())        # 实体识别    tagged_tokens = pos_tag(word_tokenize(processed_text))    processed_text = ' '.join(chunk.label() if hasattr(chunk, 'label') else chunk[0] for chunk in ne_chunk(tagged_tokens))        return processed_text

在这个修改后的函数中,我们首先导入了re模块,用于处理正则表达式匹配和替换。

然后,在preprocess_text函数中,我们使用re.sub函数和正则表达式r'http\S+|www.\S+'来匹配和替换文本中的URL链接。这样,我们可以将URL链接从文本中去除。

接下来,我们继续之前的步骤,包括去除HTML标签、移除特殊字符和标点符号、转换为小写、移除多余的空格、去除停用词、处理缩写词、词形还原和拼写纠正。

在处理缩写词时,我们创建了一个缩写词词典abbreviations,其中包含了一些常见的缩写词和对应的替换。你可以根据需要添加其他的缩写词和替换到这个词典中。

最后,我们使用pos_tag函数将文本中的单词标记词性,然后使用ne_chunk函数进行实体识别。我们使用列表推导式和条件判断语句,将识别出的实体标签保留下来,形成一个经过实体识别的文本。

这样,预处理后的文本将去除URL链接、处理缩写词,并进行其他的预处理步骤,以进一步提高文本的质量和准确性。你可以根据自己的需求进一步修改这个函数,添加其他的预处理步骤,如处理特定的符号、处理特定的文本模式等。

七、处理特定的符号、处理特定的文本模式示例代码

在这里插入图片描述根据你的需求,你可以进一步修改preprocess_text函数,添加其他的预处理步骤,如处理特定的符号、处理特定的文本模式等。下面是一个示例代码,包括处理特定符号和处理特定文本模式的预处理步骤:

import reimport nltkfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import word_tokenizefrom nltk import pos_tagfrom nltk import ne_chunkfrom nltk import downloadfrom spellchecker import SpellCheckerfrom bs4 import BeautifulSoupdef preprocess_text(text):    # 去除HTML标签    processed_text = BeautifulSoup(text, "html.parser").get_text()        # 去除URL链接    processed_text = re.sub(r'http\S+|www.\S+', '', processed_text)        # 移除文本中的特殊字符和标点符号    processed_text = re.sub(r'[^\w\s]', '', processed_text)        # 处理特定符号    processed_text = re.sub(r'\$', ' dollar ', processed_text)    processed_text = re.sub(r'%', ' percent ', processed_text)        # 将文本转换为小写    processed_text = processed_text.lower()        # 移除多余的空格    processed_text = re.sub(r'\s+', ' ', processed_text)        # 去除停用词    stop_words = set(stopwords.words('english'))    processed_text = ' '.join(word for word in processed_text.split() if word not in stop_words)        # 处理缩写词    abbreviations = {        "can't": "cannot",        "won't": "will not",        "it's": "it is",        # 添加其他缩写词和对应的替换    }    processed_text = ' '.join(abbreviations.get(word, word) for word in processed_text.split())        # 词形还原    download('averaged_perceptron_tagger')    download('wordnet')    lemmatizer = WordNetLemmatizer()    tokens = word_tokenize(processed_text)    tagged_tokens = pos_tag(tokens)    processed_text = ' '.join(lemmatizer.lemmatize(word, tag) for word, tag in tagged_tokens)        # 拼写纠正    spell = SpellChecker()    processed_text = ' '.join(spell.correction(word) for word in processed_text.split())        # 实体识别    tagged_tokens = pos_tag(word_tokenize(processed_text))processed_text = ' '.join(chunk.label() if hasattr(chunk, 'label') else chunk[0] for chunk in ne_chunk(tagged_tokens))    # 处理特定文本模式    # 示例:将日期格式统一为YYYY-MM-DD    processed_text = re.sub(r'\b(\d{1,2})[/-](\d{1,2})[/-](\d{2,4})\b', r'\3-\1-\2', processed_text)        # 示例:将电话号码格式统一为xxx-xxx-xxxx    processed_text = re.sub(r'\b(\d{3})[ -]?(\d{3})[ -]?(\d{4})\b', r'\1-\2-\3', processed_text)        return processed_text

在这个示例代码中,我们添加了两个处理特定文本模式的预处理步骤:

将日期格式统一为YYYY-MM-DD:使用正则表达式\b(\d{1,2})[/-](\d{1,2})[/-](\d{2,4})\b匹配日期格式,并使用替换模式\3-\1-\2将日期格式统一为YYYY-MM-DD。

将电话号码格式统一为xxx-xxx-xxxx:使用正则表达式\b(\d{3})[ -]?(\d{3})[ -]?(\d{4})\b匹配电话号码格式,并使用替换模式\1-\2-\3将电话号码格式统一为xxx-xxx-xxxx。

八、归纳总结

在这里插入图片描述下面是对pyttsx3中的preprocess_text函数进行归纳总结的知识点:

HTML标签去除:使用BeautifulSoup库去除文本中的HTML标签,以确保纯文本的输入。

URL链接去除:使用正则表达式re.sub函数去除文本中的URL链接。

特殊字符和标点符号去除:使用正则表达式re.sub函数去除文本中的特殊字符和标点符号。

特定符号处理:使用正则表达式re.sub函数或字符串替换操作,处理特定的符号,如将$符号替换为单词dollar,将%符号替换为单词percent,将@符号替换为单词at等。

文本转换为小写:使用str.lower方法将文本转换为小写,以统一大小写格式。

多余空格移除:使用正则表达式re.sub函数去除文本中的多余空格。

停用词去除:使用NLTK库的stopwords模块获取停用词列表,将文本中的停用词去除。

缩写词处理:定义一个包含缩写词和对应替换的字典,将文本中的缩写词替换为对应的全写形式。

词形还原:使用NLTK库的WordNetLemmatizer词形还原器,对文本中的单词进行词形还原处理。

拼写纠正:使用spellchecker库的SpellChecker类,对文本中的拼写错误进行纠正。

实体识别:使用NLTK库的ne_chunk函数对文本中的实体进行识别,例如人名、地名等。

特定文本模式处理:使用正则表达式re.sub函数,处理特定的文本模式,例如统一日期格式、电话号码格式等。

在这里插入图片描述这些预处理步骤可以根据需要进行选择和修改,以适应特定的应用场景和文本数据。预处理后的文本更干净、准确,可以更好地用于后续的语音转换。


点击全文阅读


本文链接:http://zhangshiyu.com/post/69738.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1