![](/img/trans.png)
[英]How can I extract a substring between two characters for every row of a column in a CSV file and copy those values into a new column in Python?
[英]How can I search for a substring that is between two values of a string in python?
有人可以给我一个关于执行以下操作的想法:我有一个单行文本文件,但他们向我发送了几个数据,就好像它是 xml 但在一个 txt 中。 ej:
<Respuesta><ResultEnviado><Resultado><Entrega>00123</Entrega><Refer>MueblesHiroshima</Refer><Item>34</Item><Valor>780</Valor></Resultado></ResultEnviado><EntregaItemResulados><EntregaItem><ItemId>123</ItemId><NameItem>MuebleSala</NameItem><ValorItem>180</ValorItem></EntregaItem><EntregaItem><ItemId>124</ItemId><NameItem>MuebleComedor</NameItem>ValorItem>200</ValorItem></EntregaItem><EntregaItem><ItemId>125</ItemId><NameItem>Cama</NameItem>ValorItem>200</ValorItem></EntregaItem><EntregaItem><ItemId>126</ItemId><NameItem>escritorio</NameItem>ValorItem>200</ValorItem></EntregaItem></EntregaItemResulados></Respuesta>
如您所见,它是一个扩展名为 txt 的文件。
<ResultEnviado><Resultado><Entrega>1213255654</Entrega><Refer>MueblesHiroshima</Refer><Item>34</Item><Valor>780</Valor></Resultado></ResultEnviado>
我正在使用 python 进行练习。
非常感谢您的意见或想法。
这里我们可以使用正则表达式.match()
.search()
和 .match() 函数来查找 set 标签之间的所有内容。 请注意,您需要使用import re
导入正则表达式。
有关 python 中正则表达式的更多信息:此处
import re
#open the file and read it
path = "C:/temp/file.txt"
with open(path, "r") as f:
text = f.read()
#we use regular experssion to find everything between the tags
match = re.search("<ResultEnviado>(.*?)</ResultEnviado>", text)
#prints the text if it matches
if match:
print(match.group(1))
else:
print("No match found.")
这打印:
<Resultado><Entrega>00123</Entrega><Refer>MueblesHiroshima</Refer><Item>34</Item><Valor>780</Valor></Resultado>
如果您需要更多帮助,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.