正则表达式从fi中提取字符串列表

2024-10-01 11:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个输入文件(输入文件)以下数据行的格式与以下类似:

<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Politische Inklusion"@de .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Political inclusion"@en .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Radiologische Kampfmittel"@de . 

我想提取位于outputfile中“@en”之间的英语字符串列表-英文.txt,以及位于输出文件中“@de”之间的德语字符串-数据元素.txt在

在本例中,outputfile-英文.txt应包含:

^{pr2}$

和输出文件-数据元素.txt应包含:

Politische Inklusion
Radiologische Kampfmittel 

哪种正则表达式适合这里?在


Tags: 文件数据orgcoretxthttpwwwde
2条回答

有了这样一个简单的模式,就根本不需要regex,尤其是不需要在相同的数据上重复使用不同的语言—您可以动态地流式解析并编写结果:

with open("input.txt", "r") as f:  # open the input file
    file_handles = {}  # a map of our individual output file handles
    for line in f:  # read it line by line
        rindex = line.rfind("@")  # find the last `@` character
        language = line[rindex+1:rindex+3]  # grab the following two characters as language
        if rindex != -1:  # char found, consider the line...
            lindex = line.rfind("\"", 0, rindex-1)  # find the preceding quotation
            if lindex != -1:  # found, we have a match
                if language not in file_handles:  # add a file handle for this language:
                    file_handles[language] = open("outputfile-{}.txt".format(language), "w")
                # write the found slice between `lindex` and `rindex` + a new line
                file_handles[language].write(line[lindex+1:rindex-1] + "\n")
    for handle in file_handles.values():  # lets close our output file handles
        handle.close()

它应该比regex+快得多,因为它可以与任何语言一起工作,所以如果你有...@it行,它也可以节省outputfile-it.txt。在

你可以这样做:

import re

str = """<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Politische Inklusion"@de .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Political inclusion"@en .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Radiologische Kampfmittel"@de . """

german = re.compile('"(.*)"@de')
english = re.compile('"(.*)"@en')

print german.findall(str)
print english.findall(str)

这会给你 ['Politische Inklusion','放射科医生'] 和 [“政治包容”]。 现在您只需迭代这些结果并将其写入适当的文件。在

相关问题 更多 >