使用Python在新文件中写入以determine子字符串开头的行

ftf50wuq  于 11个月前  发布在  Python
关注(0)|答案(1)|浏览(74)

我有一个txt文件,我想清理。目的是逐行读取文件,并删除所有不是由先前定义的字母(或关键字)组合开始的行。
以下是我的原始文档的示例(要清理的文档):

agigolón. (Tb. ajigolón). m. 1. El Salv., Guat., Méx. y Nic. Prisa, ajetreo. U.
m. en pl. 112. El Salv., Guat., Hond., Méx. y Nic. Apuro, aprieto. U. m. en
pl. 113. Guat., Méx. y Nic. Fatiga, cansancio.

agigotar. tr. desus. hacer gigote.
ágil. (Del lat. agilis). adj. 1. Que se mueve con soltura y rapidez. Estuvo
muy ágil y esquivó el golpe. 12. Dicho de un movimiento: Hábil y rápido.
Camina con paso ágil. 1 3. Que actúa o se desarrolla con rapidez o
prontitud. Tiene una prosa ágil.

agílibus. m. coloq. agibílibus.
agilidad. (Del lat. agilítas, -atis). f. 1. Cualidad de ágil. 12. Rel. Una de las
cuatro dotes de los cuerpos gloriosos, que consiste en la facultad de
trasladarse de un lugar a otro instantáneamente, por grande que sea la
distancia.

字符串
这是我的CDE:

from itertools import product

path = r'C:\Users\Usuario\Desktop'

spanish_alphabet = 'aábcdeéfghiíjklmnñoópqrstuúvwxyz'
keywords = [''.join(i) for i in product(spanish_alphabet, repeat = 2)]
Keywords = [i.capitalize() for i in keywords]
keywords = keywords + Keywords

A_keywords = [i for i in keywords if i.startswith(('A', 'a', 'Á', 'á'))]

with open(path + '\raw_text.txt', 'r', encoding='utf-8') as input_file:
    with open(path + '\clean_text.txt', 'w', encoding ='utf-8') as output_file:
        for line in input_file:
            # If line begins with given keyword, then write it in clean_text file
            if line.strip("\n").startswith(tuple(A_keywords)):
                output_file.write(line + '\n')


我不明白为什么我的代码不工作,结果文件是完全空的。所有以'ag'开头的行都应该写在新文件中。你能帮助我吗?

avwztpqn

avwztpqn1#

尝试(input_file.txt包含了你的问题文本):

from itertools import product

spanish_alphabet = "aábcdeéfghiíjklmnñoópqrstuúvwxyz"
keywords = ["".join(i) for i in product(spanish_alphabet, repeat=2)]
Keywords = [i.capitalize() for i in keywords]
keywords = keywords + Keywords

A_keywords = tuple(i for i in keywords if i.startswith(("A", "a", "Á", "á")))

with open("input_file.txt", "r") as f_in, open("output_file.txt", "w") as f_out:
    for line in map(str.strip, f_in):
        if line.startswith(A_keywords):
            print(line, file=f_out)

字符串
output_file.txt将包含:

agigolón. (Tb. ajigolón). m. 1. El Salv., Guat., Méx. y Nic. Prisa, ajetreo. U.
agigotar. tr. desus. hacer gigote.
ágil. (Del lat. agilis). adj. 1. Que se mueve con soltura y rapidez. Estuvo
agílibus. m. coloq. agibílibus.
agilidad. (Del lat. agilítas, -atis). f. 1. Cualidad de ágil. 12. Rel. Una de las

相关问题