鉴于infile包含:
aaaaaaa"pic01.jpg"bbbwrtwbbbsize 110KB
aawerwefrewqa"pic02.jpg"bbbertebbbsize 100KB
atyrtyruraa"pic03.jpg"bbbwtrwtbbbsize 190KB
如何获取outfile:
pic01.jpg 110KB
pic02.jpg 100KB
pic03.jpg 190KB
我的代码是:
with open ('test.txt', 'r') as infile, open ('outfile.txt', 'w') as outfile:
for line in infile:
lines_set1 = line.split ('"')
lines_set2 = line.split (' ')
for item_set1 in lines_set1:
for item_set2 in lines_set2:
if item_set1.endswith ('.jpg'):
if item_set2.endswith ('KB'):
outfile.write (item_set1 + ' ' + item_set2 + '\n')
我的代码有什么问题,请帮忙! 这个问题已经解决了: what is wrong in the code written inpython
答案 0 :(得分:3)
通常你可以在没有正则表达式的情况下解决字符串操作问题,因为Python有一个很棒的字符串库。在您的情况下,只需使用不同的分隔符(引号和空格)两次调用str.split
即可解决您的问题
演示
>>> st = """aaaaaaa"pic01.jpg"bbbwrtwbbbsize 110KB
aawerwefrewqa"pic02.jpg"bbbertebbbsize 100KB
atyrtyruraa"pic03.jpg"bbbwtrwtbbbsize 190KB"""
>>> def foo(st):
#Split the string based on quotation mark
_, fname, rest = st.split('"')
#from the residual part split based on space
#and select the last part
rest = rest.split()[-1]
#join and return fname and the residue
return ' '.join([fname, rest])
>>> for e in st.splitlines():
print foo(e)
pic01.jpg 110KB
pic02.jpg 100KB
pic03.jpg 190KB
答案 1 :(得分:3)
正则表达式会更容易:
with open ('test.txt', 'r') as infile, open ('outfile.txt', 'w') as outfile:
for line in infile:
m = re.search('"([^"]+)".*? (\d+.B)', line)
if m:
outfile.write(m.group(1) + ' ' + m.group(2) + '\n')
答案 2 :(得分:1)
你可以在这里使用正则表达式和str.rsplit
,你的代码似乎对这个简单的任务来说太过分了:
>>> import re
>>> strs = 'aaaaaaa"pic01.jpg"bbbwrtwbbbsize 110KB\n'
>>> name = re.search(r'"(.*?)"', strs).group(1)
>>> size = strs.rsplit(None, 1)[-1]
>>> name, size
('pic01.jpg', '110KB')
或
>>> name, size = re.search(r'"(.*?)".*?(\w+)$', strs).groups()
>>> name, size
('pic01.jpg', '110KB')
现在使用字符串格式:
>>> "{} {}\n".format(name, size) #write this to file
'pic01.jpg 110KB\n'