提问人:Javi 提问时间:11/15/2023 最后编辑:Javi 更新时间:11/15/2023 访问量:43
使用 Python 在新文件中写入以 determine 子字符串开头的行
Write lines starting with a determine substring in a new file with Python
问:
我有一个要清理的 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”开头的行都应写入新文件中。你可以帮我吗?
答:
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
上一个:选项相对于其参数类型是不变的?
下一个:查找最后一个单词的长度
评论
if line.strip()[:2] in A_keywords:
'\raw_text.txt'
\r