社区所有版块导航
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 年前 • 1630 次点击  

我需要忽略当有人进入和离开频道时的线路,正如你在下面的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 年前
ljdyer
Reply   •   1 楼
ljdyer    4 年前

你可以在第一次阅读之前使用列表理解 for 循环以过滤掉不需要的线条。

with open('txtfile.txt', encoding='utf-8') as sherr:
    row = 1
    column = 1
    ws = wb.active

    lines = [line for line in sherr.readlines()
            if 'entered the channel' not in line
            and 'left the channel' not in line]

    for line in lines:

注意我变了 sherr 到 lines 在比赛开始的时候 对于 环

上面的条件是,如果行中包含“进入频道”或“离开频道”的字符串,则应忽略这些行,但请注意,如果有人碰巧将这些字符串作为对话的一部分,这可能会导致不必要的行为。如果有必要,可以通过检查行是否也以数字等开头,或者使用正则表达式,使其更加健壮。