Python脚本之文本处理和操作_python文本处理教程
Python脚本之文本处理和操作
计算文本文件中的字数
#计算文本文件的数字
def count_words(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
text=f.read()
word_count=len(text.split())
return word_count
if __name__ == '__main__':
count_words(file_path="")
说明:此脚本读取文本文件并计算其包含的单词数,适用于快速分析文本文件内容。
文件中的文本查找和替换
def find_replace(file_path,search_text,replace_text):
"""
说明:此脚本能搜索文件中的特定文本并将其替换为所需的文本,适用于批量替换文本的场景。
:param file_path:
:param search_text:
:param replace_text:
:return:
"""
with open(file_path,'r',encoding='utf-8') as f:
text=f.read()
modified_text=text.replace(search_text,replace_text)
with open(file_path,'w',encoding='utf-8') as f:
f.write(modified_text)
说明:此脚本能搜索文件中的特定文本并将其替换为所需的文本,适用于批量替换文本的场景。
生成随机文本
import random
import string
def generate_random_text(length):
"""
说明:此脚本生成指定长度的随机文本,适用于测试和模拟场景。
:param length:
:return:
"""
letters = string.ascii_letters+string.digits+string.punctuation
random_text = ''.join(random.choice(letters) for i in range(length))
return random_text
if __name__ == '__main__':
text=generate_random_text(10)
print(text)
说明:此脚本生成指定长度的随机文本,适用于测试和模拟场景。