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')
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).'
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()
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.
我认为这将是最直接的解决方案:
这是使用regular expression的理想时机
下面是regex
(min.*\.)
的工作原理:(
打开一个捕获组min
按字面意思匹配字符min
(不区分大小写,因为我们使用了re.IGNORECASE
).*
{\.
逐字匹配字符.
(不区分大小写)您可以在字符串列表上使用
partition
方法str.partition(sep)
您只需将最后两个元组(即从
MIN
)连接起来,然后使用join
构建一个新字符串相关问题 更多 >
编程相关推荐