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

Write lines starting with a determine substring in a new file with Python

提问人:Javi 提问时间:11/15/2023 最后编辑:Javi 更新时间:11/15/2023 访问量:43

问:

我有一个要清理的 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”开头的行都应写入新文件中。你可以帮我吗?

python-itertools TXT公司 数据预处理

评论

1赞 LMC 11/15/2023
文本示例不应是图像
0赞 Andrej Kesely 11/15/2023
编辑您的问题,不要将输入文本作为图像,而是作为纯文本。
0赞 Javi 11/15/2023
@LMC这是 txt 格式的真实文本的屏幕截图,以便您可以看到它在内部的样子
1赞 JonSG 11/15/2023
if line.strip()[:2] in A_keywords:
2赞 Barmar 11/15/2023
您确定要打开输入文件吗? 创建一个包含回车符的路径名,因为是一个转义序列。'\raw_text.txt'\r

答:

0赞 Andrej Kesely 11/15/2023 #1

尝试(包含问题中的文本):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