gpt4 book ai didi

Python:读取文本文件的一部分

转载 作者:太空狗 更新时间:2023-10-30 02:06:46 25 4
gpt4 key购买 nike

大家好

我是 Python 和编程的新手。我需要读取大文本文件的 block ,格式如下所示:

<word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/>

我需要formlemmapostag 信息。例如对于以上,我需要 hibernishibernus1n-p---nb-

如何告诉 python 读取直到到达 form,向前读取直到到达引号 " 然后读取引号之间的信息 "hibernis"? 真的很纠结。

到目前为止,我的尝试是删除标点符号、拆分句子,然后从列表中提取我需要的信息。虽然无法让 python 遍历整个文件,但我只能让它工作 1 行。我的代码如下:

f=open('blank.txt','r')
quotes=f.read()
noquotes=quotes.replace('"','')
f.close()

rf=open('blank.txt','w')
rf.write(noquotes)
rf.close()

f=open('blank.txt','r')
finished = False
postag=[]
while not finished:
line=f.readline()
words=line.split()
postag.append(words[4])
postag.append(words[6])
postag.append(words[8])
finished=True

欢迎任何反馈/批评

谢谢

最佳答案

如果是 XML,使用 ElementTree解析它:

from xml.etree import ElementTree

line = '<word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head="7" relation="ADV"/>'

element = ElementTree.fromstring(line)

对于每个 XML 元素,您可以轻松提取名称和所有属性:

>>> element.tag
'word'
>>> element.attrib
{'head': '7', 'form': 'hibernis', 'postag': 'n-p---nb-', 'lemma': 'hibernus1', 'relation': 'ADV', 'id': '8'}

因此,如果您有一个包含一堆 word XML 元素的文档,像这样的东西将从每个元素中提取您想要的信息:

from xml.etree import ElementTree

XML = '''
<words>
<word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head="7" relation="ADV"/>
</words>'''

root = ElementTree.fromstring(XML)

for element in root.findall('word'):
form = element.attrib['form']
lemma = element.attrib['lemma']
postag = element.attrib['postag']

print form, lemma, postag

如果您只有一个文件名,请使用 parse() 而不是 fromstring()

关于Python:读取文本文件的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/964993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com