最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python自動化讀取txt文件數(shù)據的8個實用腳本

 更新時間:2025年09月05日 09:47:33   作者:Python資訊站  
這篇文章主要為大家詳細介紹了Python自動化讀取txt文件數(shù)據的8個實用腳本,包括讀取,對比,轉換格式等,感興趣的小伙伴可以跟隨小編一起學習一下

這次和大家分享txt辦公自動化,包括讀取、對比、過濾、合并、轉換格式、提取數(shù)據、統(tǒng)計詞頻、生成報告等。

準備工作:安裝所需的Python庫

  • re(正則表達式操作,用于復雜文本匹配)
  • csv(處理CSV文件)
  • json(處理JSON文件)
  • collections(用于統(tǒng)計詞頻)
  • matplotlibwordcloud(生成詞云圖)

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如何訪問字符串中的值

    Python如何訪問字符串中的值

    這篇文章主要介紹了Python如何訪問字符串中的值,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-02-02
  • pytorch 數(shù)據處理:定義自己的數(shù)據集合實例

    pytorch 數(shù)據處理:定義自己的數(shù)據集合實例

    今天小編就為大家分享一篇pytorch 數(shù)據處理:定義自己的數(shù)據集合實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • Python實現(xiàn)Excel表格轉HTML

    Python實現(xiàn)Excel表格轉HTML

    Excel工作簿是常用的表格格式,廣泛用于組織、分析及展示數(shù)據,這篇文章主要為大家詳細介紹了如何使用Python將Excel工作簿或工作表轉換為HTML文件,需要的可以參考下
    2024-03-03
  • 詳解Python 裝飾器執(zhí)行順序迷思

    詳解Python 裝飾器執(zhí)行順序迷思

    這篇文章主要介紹了詳解Python 裝飾器執(zhí)行順序迷思,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08
  • Python selenium抓取虎牙短視頻代碼實例

    Python selenium抓取虎牙短視頻代碼實例

    這篇文章主要介紹了Python selenium抓取虎牙短視頻代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-03-03
  • Python中的asyncio代碼詳解

    Python中的asyncio代碼詳解

    asyncio 是用來編寫 并發(fā) 代碼的庫,使用 async/await 語法。 asyncio 被用作多個提供高性能 Python 異步框架的基礎,包括網絡和網站服務,數(shù)據庫連接庫,分布式任務隊列等等。這篇文章主要介紹了Python中的asyncio,需要的朋友可以參考下
    2019-06-06
  • pow在python中的含義及用法

    pow在python中的含義及用法

    在本篇文章里小編給各位分享了關于pow在python中是什么意思的相關知識點內容,有需要的朋友們參考學習下。
    2019-07-07
  • Python數(shù)據類型--字典dictionary

    Python數(shù)據類型--字典dictionary

    這篇文章主要介紹了Python數(shù)據類型字典dictionary,字典是另一種可變容器模型,且可存儲任意類型對象。下面詳細內容需要的小伙伴可以參考一下,希望對你有所幫助
    2022-02-02
  • Pytorch使用DataLoader實現(xiàn)批量加載數(shù)據

    Pytorch使用DataLoader實現(xiàn)批量加載數(shù)據

    這篇文章主要介紹了Pytorch使用DataLoader實現(xiàn)批量加載數(shù)據方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • 淺談python中常用的excel模塊庫

    淺談python中常用的excel模塊庫

    本文主要介紹了python中常用的excel模塊庫,感興趣的同學,可以參考下。
    2021-06-06

最新評論

航空| 横山县| 武义县| 阿拉尔市| 璧山县| 边坝县| 兴和县| 德清县| 进贤县| 五常市| 乌兰浩特市| 洮南市| 阿图什市| 房产| 万州区| 区。| 长沙县| 卢氏县| 东辽县| 托克逊县| 临高县| 汾西县| 正安县| 鞍山市| 阿坝县| 将乐县| 镇安县| 谢通门县| 夏津县| 攀枝花市| 新绛县| 三明市| 公安县| 金堂县| 岚皋县| 广宗县| 奈曼旗| 梨树县| 永康市| 陈巴尔虎旗| 梧州市|