从作为csv fi一部分的字符串中修剪不同子字符串的列表

2024-04-26 11:12:53 发布

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


Tags: python
1条回答
网友
1楼 · 发布于 2024-04-26 11:12:53

使用正则表达式替换:

from io import StringIO
import csv
import re

s = '''Name       Att1   Att2   Att3
c.45fs>96
c.67fs*>87
c.89fs*98'''

with StringIO(s) as f:
    reader = csv.DictReader(f, skipinitialspace=True, delimiter=' ')
    pat = re.compile(r'(fs\*?>?).+$')
    for r in reader:
        r['Name'] = pat.sub('\\1', r['Name'])
        print(r.values())

样本输出:

odict_values(['c.45fs>', None, None, None])
odict_values(['c.67fs*>', None, None, None])
odict_values(['c.89fs*', None, None, None])

相关问题 更多 >