社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python中忽略从txt文件到excel文件的一行

kyjsml • 4 年前 • 1625 次点击  

我需要忽略当有人进入和离开频道时的线路,正如你在下面的txt文件中看到的那样。

7:52:01 AM sherr entered the channel
7:52:05 AM sherr
hello GOOD morning .
おはようございます。
7:52:09 AM sherr
Who ?
誰?
7:52:16 AM sherr
OK .
わかりました。
7:52:25 AM sherr left the channel.
7:52:32 AM gigi entered the channel
7:52:45 AM gigi
OK .
わかりました。

我的代码应该输出excel文件,在每3行中,它们位于同一行,第1列第1行,第2列第2行,第3列第3行。但我需要忽略那些进入频道和离开频道的线路。我应该补充什么? 我的代码如下所示。

from openpyxl import Workbook
import copy

wb = Workbook()

with open('txtfile.txt', encoding='utf-8') as sherr:
    row = 1
    column = 1
    ws = wb.active
    for line in sherr:
        if column == 1:
            ## split the line and rejoin
            value = " ".join(line.strip().split(' ')[1:])
        else:
            value = line.strip()
            
        ws.cell(row=row, column=column, value=value)
        
        if (column := column + 1) > 3:
            row += 1
            column = 1
 
    for row in ws.iter_rows():
        for cell in row:      
            alignment = copy.copy(cell.alignment)
            alignment.wrapText=True
            cell.alignment = alignment
            
    for column_cells in ws.columns:
        length = max(len(str(cell.value)) for cell in column_cells)
        ws.column_dimensions[column_cells[0].column_letter].width = length

    wb.save('txt_to_exl.xlsx')
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132219
文章 [ 1 ]  |  最新文章 4 年前