本文主要是介绍文本预处理1--去除#和句号之间内容,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.针对文本里特定两个符号之间内容的中文进行去除,本次选取#和句号之间的内容进行去除。
2.大家可以根据自己的实际需求修改代码实现自己的文本内容的整理。
3.下面是去除#和句号之间内容的python代码:其中读取的是txt文本,处理后的内容写回原txt文件。
import os
def remove_content_between_hash_and_period(input_text):start_search_pos = 0while True:hash_pos = input_text.find('#', start_search_pos)if hash_pos == -1:breakperiod_pos = input_text.find('。', hash_pos)if period_pos == -1:input_text = input_text[:hash_pos]breakinput_text = input_text[:hash_pos] + input_text[period_pos + 1:]start_search_pos = hash_posreturn input_textdef process_txt_files(folder_path):for filename in os.listdir(folder_path):if filename.endswith('.txt'):file_path = os.path.join(folder_path, filename)with open(file_path, 'r', encoding='utf-8') as file:content = file.read()processed_content = remove_content_between_hash_and_period(content)# 可选:将处理后的内容写回文件with open(file_path, 'w', encoding='utf-8') as file:file.write(processed_content)# 打印处理后的内容(如果需要)# print(f'Processed content of {filename}:')# print(processed_content)# 替换为你的文件夹路径
folder_path = "C:\\Users\\lenovo\\Desktop"
process_txt_files(folder_path)
这篇关于文本预处理1--去除#和句号之间内容的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!