我有如下所示的.txt文件,我想获取从关键字“Min”到最后一个的所有字符串

2024-06-01 07:13:10 发布

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

我有如下所示的.txt文件,我想获取文件中从关键字“Min”到最后一个“.”的所有字符串,并使用python将其转储到另一个.txt文件中

      Rahul            MIN Y(03).                               
       Annie          MIN Y(15).                               
      Amit             MIN Y(02).(gg).                               
       Jai                MIN Y(06).                               
     Antony              MIN Y(160).

预期产出: 明Y(03)。 MIN Y(15)。 最小Y(02)。(gg)。 明Y(06)。 MIN Y(160)


Tags: 文件字符串txt关键字minggamitantony
3条回答

我认为这将是最直接的解决方案:

with open('infile.txt', 'r') as f_in:
  with open('outfile.txt', 'w') as f_out:
    for line in f_in:
        subline = line.split('MIN')[-1].split('.')[0]
        f_out.write(f'{subline}\n')

这是使用regular expression的理想时机

s = """      Rahul            MIN Y(03).                               
       Annie          MIN Y(15).                               
      Amit             MIN Y(02).(gg).                               
       Jai                MIN Y(06).                               
     Antony              MIN Y(160).
"""
# Import python's regex library
import re

# Create our pattern
pat = re.compile(r"(min.*\.)", flags=re.IGNORECASE)

# Find all the pattern matches in the string `s`
for m in pat.findall(s):
    print(m)

# 'MIN Y(03).'
# 'MIN Y(15).'
# 'MIN Y(02).(gg).'
# 'MIN Y(06).'
# 'MIN Y(160).'

下面是regex(min.*\.)的工作原理:

  • (打开一个捕获组
  • min按字面意思匹配字符min(不区分大小写,因为我们使用了re.IGNORECASE
  • .*{}匹配任何字符,并且{}告诉它尽可能多地匹配零次和无限次
  • \.逐字匹配字符.(不区分大小写)
with open('/path/to/read/txt','r') as f:
    l=f.readlines()
    l1=[" ".join(i.partition('MIN')[1::]).strip(' ') for i in l ]
    f1=open('/path/to/write/txt','w')
    for i in l1:
        f1.write(i)
    f1.close()

您可以在字符串列表上使用partition方法

str.partition(sep)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.

[('Rahul', 'MIN', ' Y(03). \n')........]

您只需将最后两个元组(即从MIN)连接起来,然后使用join构建一个新字符串

相关问题 更多 >