在python中输出具有多个条件的文件?
鉴于内嵌包含:在python中输出具有多个条件的文件?,python,Python,鉴于内嵌包含: aaaaaaa"pic01.jpg"bbbwrtwbbbsize 110KB aawerwefrewqa"pic02.jpg"bbbertebbbsize 100KB atyrtyruraa"pic03.jpg"bbbwtrwtbbbsize 190KB 如何以以下方式获取输出文件: pic01.jpg 110KB pic02.jpg 100KB pic03.jpg 190KB 我的代码是: with open ('test.txt', 'r') as infile, ope
aaaaaaa"pic01.jpg"bbbwrtwbbbsize 110KB
aawerwefrewqa"pic02.jpg"bbbertebbbsize 100KB
atyrtyruraa"pic03.jpg"bbbwtrwtbbbsize 190KB
如何以以下方式获取输出文件:
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')
我的代码有什么问题,请帮助!
问题已在此处解决:
您可以使用regex和
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')
或
现在使用字符串格式:
>>> "{} {}\n".format(name, size) #write this to file
'pic01.jpg 110KB\n'
通常,您可以在不使用正则表达式的情况下解决字符串操作问题,因为Python有一个惊人的字符串库。在您的情况下,只需使用不同的分隔符(引号和空格)调用两次
str.split
,就可以解决您的问题
演示
正则表达式将更容易:
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')
我想像我的问题@Ashwini Chaudhary一样编写outfile.txt谢谢,但是我的代码不能用re来更正吗@Ashwini Chaudhary我的问题是关于在我的代码@Ashwini中使用multiple line.splitChaudhary@leanne这使你的问题成为@Eric的完美例子outfile是空白的不在我发布的链接中它不是。。。
>>> 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
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')