Python解析文本在单词后删除所有内容

2024-04-29 13:44:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个巨大的TXT文件,有不同的列数。在

jero, kor@gmail.com, 44d448e4d, team, 0, 6, 5, 2, s, s, s, none, none
jader, lda@gmail.com, d44a88x, team, 0, none, 48, 95, oled
etc for 15000 lines

我想删掉每一行中“团队”一词后的所有内容。我试过几次正则表达式,但都没成功。在

谢谢你!在


Tags: 文件txtcomnoneforetcgmailteam
3条回答

好吧,如果您要解析一个CSV文件,让我们使用dedicated module

import csv

for row in csv.reader(your_file, skipinitialspace=True):
    if 'team' in row:
        row = row[:row.index('team')+1]
    print ', '.join(row)

{cd1>这样可以节省所有的麻烦

用户不需要为此使用regex,有一个直接的解决方案。在

with open('file.txt') as f:
    for line in f:
        i = line.split('team')[0] + "team"

你不需要使用正则表达式。使用^{}

>>> line = 'jero, kor@gmail.com, 44d448e4d, team, 0, 6, 5, 2, s, s, s, none, none'
>>> a, sep, _ = line.partition('team')
>>> a
'jero, kor@gmail.com, 44d448e4d, '
>>> sep
'team'
>>> a + sep
'jero, kor@gmail.com, 44d448e4d, team'

^{pr2}$

更新

要解决@DSM提到的问题:在包含team的其他字段上拆分:

with open('file.txt') as f:
    for line in f:
        a, sep, _ = line.partition(', team,')
        line = a + sep
        # Do something with line

相关问题 更多 >