Python自動化讀取txt文件數(shù)據的8個實用腳本
這次和大家分享txt辦公自動化,包括讀取、對比、過濾、合并、轉換格式、提取數(shù)據、統(tǒng)計詞頻、生成報告等。
準備工作:安裝所需的Python庫
re(正則表達式操作,用于復雜文本匹配)csv(處理CSV文件)json(處理JSON文件)collections(用于統(tǒng)計詞頻)matplotlib和wordcloud(生成詞云圖)
1.讀取txt內容
1.1 逐行讀取txt文件
在數(shù)據處理的第一步就是讀取txt文件。以下是逐行讀取txt文件的示例代碼:
def read_txt_file_by_line(filepath):
with open(filepath, 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
# 示例調用
read_txt_file_by_line('example.txt')
1.2 讀入整個txt文件內容
如果需要將整個txt文件的內容讀入到一個字符串中,可以使用以下代碼:
def read_txt_file(filepath):
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
return content
# 示例調用
content = read_txt_file('example.txt')
print(content)
2. 對比兩個txt文件內容
2.1 基本文本對比
有時候我們需要比較兩個txt文件內容是否相同,以下代碼可以實現(xiàn)這一功能:
def compare_txt_files(file1, file2):
with open(file1, 'r', encoding='utf-8') as f1, open(file2, 'r', encoding='utf-8') as f2:
content1 = f1.readlines()
content2 = f2.readlines()
for line1, line2 in zip(content1, content2):
if line1 != line2:
print(f'Difference found:\nFile1: {line1}\nFile2: {line2}')
# 示例調用
compare_txt_files('file1.txt', 'file2.txt')
2.2 差異高亮顯示
為了更直觀地顯示txt文件之間的差異,可以用差異高亮顯示的方法。我們使用difflib庫來實現(xiàn):
import difflib
def highlight_differences(file1, file2):
with open(file1, 'r', encoding='utf-8') as f1, open(file2, 'r', encoding='utf-8') as f2:
content1 = f1.readlines()
content2 = f2.readlines()
diff = difflib.unified_diff(content1, content2, fromfile='file1', tofile='file2')
for line in diff:
print(line)
# 示例調用
highlight_differences('file1.txt', 'file2.txt')
3. txt文件內容過濾
3.1 過濾特定關鍵字行
在處理txt文件時,可能需要過濾掉包含特定關鍵字的行。以下是一個示例代碼:
def filter_lines_by_keyword(filepath, keyword):
with open(filepath, 'r', encoding='utf-8') as file:
lines = file.readlines()
filtered_lines = [line for line in lines if keyword not in line]
return filtered_lines
# 示例調用
filtered = filter_lines_by_keyword('example.txt', 'filter_keyword')
for line in filtered:
print(line.strip())
3.2 過濾空行和注釋行
有時候需要過濾掉空行和注釋行(比如以#開頭的行)。以下是實現(xiàn)這一功能的代碼:
def filter_empty_and_comment_lines(filepath):
with open(filepath, 'r', encoding='utf-8') as file:
lines = file.readlines()
filtered_lines = [line for line in lines if line.strip() and not line.strip().startswith('#')]
return filtered_lines
# 示例調用
filtered = filter_empty_and_comment_lines('example.txt')
for line in filtered:
print(line.strip())
4. 合并多個txt文件
4.1 簡單合并
將多個txt文件的內容簡單合并成一個文件,可以使用以下代碼:
def merge_txt_files(file_list, output_file):
with open(output_file, 'w', encoding='utf-8') as outfile:
for file in file_list:
with open(file, 'r', encoding='utf-8') as infile:
outfile.write(infile.read())
outfile.write('\n')
# 示例調用
merge_txt_files(['file1.txt', 'file2.txt', 'file3.txt'], 'merged.txt')
4.2 按行混合合并
如果需要按行混合合并多個文件的內容,可以使用以下代碼:
def merge_files_by_line(file_list, output_file):
files = [open(file, 'r', encoding='utf-8') for file in file_list]
with open(output_file, 'w', encoding='utf-8') as outfile:
while True:
lines = [file.readline() for file in files]
if all(line == '' for line in lines):
break
for line in lines:
if line:
outfile.write(line.strip() + '\n')
for file in files:
file.close()
# 示例調用
merge_files_by_line(['file1.txt', 'file2.txt', 'file3.txt'], 'merged_by_line.txt')
5. 將txt文件轉換為其他格式
5.1 轉換為csv格式
有時候我們需要將txt文件的內容轉換成csv格式以便進行數(shù)據處理或分析,下面是相關代碼示例:
import csv
def txt_to_csv(txt_file, csv_file):
with open(txt_file, 'r', encoding='utf-8') as infile, open(csv_file, 'w', newline='', encoding='utf-8')
as outfile:
writer = csv.writer(outfile)
for line in infile:
writer.writerow(line.strip().split())
# 示例調用
txt_to_csv('example.txt', 'output.csv')
這段代碼將txt文件的內容逐行讀取,并按空格或制表符拆分成csv格式。
5.2 轉換為json格式
除了csv格式,JSON格式也是常用的數(shù)據存儲格式。以下是將txt文件轉換為JSON格式的代碼示例:
import json
def txt_to_json(txt_file, json_file):
data = []
with open(txt_file, 'r', encoding='utf-8') as infile:
for line in infile:
data.append(line.strip())
with open(json_file, 'w', encoding='utf-8') as outfile:
json.dump(data, outfile, indent=4)
# 示例調用
txt_to_json('example.txt', 'output.json')
這段代碼將txt文件的每一行內容作為JSON數(shù)組里的一個元素進行存儲。
6. 從txt文件提取數(shù)據
6.1 提取特定模式的文本
有時候我們需要從txt文件中提取符合特定模式的文本,可以使用正則表達式(re庫)來實現(xiàn)。以下代碼示例演示如何提取符合某個模式的文本:
import re
def extract_pattern_from_txt(pattern, txt_file):
matches = []
with open(txt_file, 'r', encoding='utf-8') as file:
content = file.read()
matches = re.findall(pattern, content)
return matches
# 示例調用,提取所有的數(shù)字
pattern = r'\d+'
matches = extract_pattern_from_txt(pattern, 'example.txt')
print("Match found:", matches)
6.2 提取郵件地址或URL
我們可以使用類似的方法來提取郵件地址或URL:
def extract_emails_and_urls(txt_file):
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
url_pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
with open(txt_file, 'r', encoding='utf-8') as file:
content = file.read()
emails = re.findall(email_pattern, content)
urls = re.findall(url_pattern, content)
return emails, urls
# 示例調用
emails, urls = extract_emails_and_urls('example.txt')
print("Emails found:", emails)
print("URLs found:", urls)
7. 統(tǒng)計txt文件中的詞頻
7.1 統(tǒng)計單詞出現(xiàn)次數(shù)
我們可以統(tǒng)計txt文件中單詞的出現(xiàn)頻次,并對其進行排序。以下代碼示例展示如何實現(xiàn):
from collections import Counter
def count_word_frequency(txt_file):
with open(txt_file, 'r', encoding='utf-8') as file:
words = file.read().split()
word_freq = Counter(words)
return word_freq
# 示例調用
word_freq = count_word_frequency('example.txt')
for word, freq in word_freq.most_common():
print(f'{word}: {freq}')
7.2 生成詞云圖
對于可視化效果,可以生成詞云圖來顯示詞頻分布:
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def generate_word_cloud(txt_file):
with open(txt_file, 'r', encoding='utf-8') as file:
text = file.read()
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
# 示例調用
generate_word_cloud('example.txt')
8. 自動生成txt報告
8.1 從模板生成報告
可以使用txt模板生成報告,將動態(tài)數(shù)據填充到模板中。以下示例展示如何從模板生成報告:
def generate_report_from_template(template_file, output_file, data):
with open(template_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8')
as outfile:
content = infile.read()
for key, value in data.items():
content = content.replace(f'{{{{ {key} }}}}', str(value))
outfile.write(content)
# 示例調用
data = {
'name': 'Alice',
'date': '2024-08-17',
'summary': 'This is a summary of the report.'}
generate_report_from_template('template.txt', 'report.txt', data)
8.2 動態(tài)生成報告內容
有時候需要動態(tài)生成報告的內容,以下示例展示如何實現(xiàn):
def generate_dynamic_report(output_file, sections):
with open(output_file, 'w', encoding='utf-8') as outfile:
for section in sections:
outfile.write(f'# {section["title"]}\n\n')
outfile.write(f'{section["content"]}\n\n')
# 示例調用
sections = [{"title": "Introduction",
"content": "This is the introduction section of the report."},
{"title": "Data Analysis",
"content": "This section contains the analysis of the data."}]
generate_dynamic_report('dynamic_report.txt', sections)
9. 最后
通過這篇文章,你已經了解了使用Python進行txt文件的多種辦公自動化方法,包括讀取、對比、過濾、合并、轉換格式、提取數(shù)據、統(tǒng)計詞頻、生成報告等。這些技巧不僅能提高效率,還能為數(shù)據分析工作打下堅實的基礎。
到此這篇關于Python自動化讀取txt文件數(shù)據的8個實用腳本的文章就介紹到這了,更多相關Python讀取txt文件數(shù)據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python讀取txt文件數(shù)據的方法(用于接口自動化參數(shù)化數(shù)據)
- python讀取txt數(shù)據的操作步驟
- 教你利用python如何讀取txt中的數(shù)據
- Python實現(xiàn)讀取txt文件中的數(shù)據并繪制出圖形操作示例
- python讀取txt文件并取其某一列數(shù)據的示例
- python讀取csv和txt數(shù)據轉換成向量的實例
- python使用numpy讀取、保存txt數(shù)據的實例
- 對python .txt文件讀取及數(shù)據處理方法總結
- Python實現(xiàn)讀取TXT文件數(shù)據并存進內置數(shù)據庫SQLite3的方法
相關文章
pytorch 數(shù)據處理:定義自己的數(shù)據集合實例
今天小編就為大家分享一篇pytorch 數(shù)據處理:定義自己的數(shù)據集合實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Pytorch使用DataLoader實現(xiàn)批量加載數(shù)據
這篇文章主要介紹了Pytorch使用DataLoader實現(xiàn)批量加載數(shù)據方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02

