Python-从文本文件中的行中删除引号中的任何内容
Python-Delete anything in quotes from line in text file
我正在尝试从文件中删除引号内的任何文本(以及引号本身)。
基本上我需要这个:
A A2A|"Dm"A2A "C"G2E|"Dm"D2D A,2D|
要变成这样:
A A2A|A2A G2E|D2D A,2D|
这是我最初尝试的代码片段:
def conversion():
with open(abc + .'txt') as infile, open(abc + '.tmp', 'w') as outfile:
for line in infile:
#Delete anything inside of quotes after the header
if '"' + '' in line:
line = line.replace('"' + '', '')
outfile.write(line)
#Write everything else
else:
outfile.write(line)
conversion()
这会删除引号,但会保留其中的所有内容。
如果我改变
line = line.replace('"' +'','')
到
line = line.replace('"' + "Dm" + '"', '')
我可以去掉任何包含 "Dm" 的东西,理论上我可以为每个可能的组合编程,但这将是一个巨大的 PITA,我想允许人为错误(例如有人写 "Dma" 而不是 "Dmaj").
我也尝试过使用正则表达式,但老实说我不知道我在用它做什么。
def conversion():
with open(abc + '.txt') as infile, open(abc + '.tmp', 'w') as outfile:
for line in infile:
#Delete anything inside of quotes after the header
if '"' in line:
re.sub('".+"', '', line)
outfile.write(line)
#Write everything else
else:
outfile.write(line)
conversion()
这似乎没有任何作用,我已经查看了 python 文档,但没有示例说明如何在我尝试的上下文中使用它。
re.sub()
returns 已编辑的行,它没有就地编辑。
line = re.sub('".*?"', '', line)
outfile.write(line)
而且您的正则表达式会匹配引号,所以我对其进行了编辑以使其成为 non-greedy。
我正在尝试从文件中删除引号内的任何文本(以及引号本身)。
基本上我需要这个:
A A2A|"Dm"A2A "C"G2E|"Dm"D2D A,2D|
要变成这样:
A A2A|A2A G2E|D2D A,2D|
这是我最初尝试的代码片段:
def conversion():
with open(abc + .'txt') as infile, open(abc + '.tmp', 'w') as outfile:
for line in infile:
#Delete anything inside of quotes after the header
if '"' + '' in line:
line = line.replace('"' + '', '')
outfile.write(line)
#Write everything else
else:
outfile.write(line)
conversion()
这会删除引号,但会保留其中的所有内容。
如果我改变
line = line.replace('"' +'','')
到
line = line.replace('"' + "Dm" + '"', '')
我可以去掉任何包含 "Dm" 的东西,理论上我可以为每个可能的组合编程,但这将是一个巨大的 PITA,我想允许人为错误(例如有人写 "Dma" 而不是 "Dmaj").
我也尝试过使用正则表达式,但老实说我不知道我在用它做什么。
def conversion():
with open(abc + '.txt') as infile, open(abc + '.tmp', 'w') as outfile:
for line in infile:
#Delete anything inside of quotes after the header
if '"' in line:
re.sub('".+"', '', line)
outfile.write(line)
#Write everything else
else:
outfile.write(line)
conversion()
这似乎没有任何作用,我已经查看了 python 文档,但没有示例说明如何在我尝试的上下文中使用它。
re.sub()
returns 已编辑的行,它没有就地编辑。
line = re.sub('".*?"', '', line)
outfile.write(line)
而且您的正则表达式会匹配引号,所以我对其进行了编辑以使其成为 non-greedy。