【问题标题】:Python - Parsing text - Cut everything after a wordPython - 解析文本 - 在一个单词后剪切所有内容
【发布时间】:2015-01-25 02:14:50
【问题描述】:

我有这个包含不同列号的巨大 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

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

谢谢!

【问题讨论】:

  • 我会远离正则表达式。阿尔菲的回答似乎很有希望
  • 换一种说法:你想保留前三列?如果某人的电子邮件地址是 mad_murdock@a_team.org,则在 team 上拆分或替换的每个当前答案都将失败。

标签: python string file parsing


【解决方案1】:

对此无需用户正则表达式,有一个直接的解决方案。

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

【讨论】:

  • 太棒了,它正在工作!十分感谢。我不能给你我的支持,因为我是这里的新手,但如果你有 Facebook 或 Twitter,我会很高兴给你一个关注。最佳
【解决方案2】:

好吧,如果您要解析 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)

这让您免于使用jero_team, kor@team.com, 44d448e4d, team, 0, one_more, team, 5, 2 等输入的所有麻烦

【讨论】:

  • 也可以使用del声明:del row[row.index('team') + 1:]
  • @falsetru:当然,一个更好的主意是使用try-except pass 而不是if 以避免扫描列表两次。
【解决方案3】:

您不需要使用正则表达式。使用str.partition

>>> 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'

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

更新

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

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

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 2021-12-07
    • 2022-11-21
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多