Python:搜索一些单词并删除.txt文件中的完整行

时间:2017-07-12 10:58:36

标签: python

我有文本文件,有时可能有一行过多,我必须删除它。并非总是如此,但每次都需要检查它。

这个短语在开头总是包含相同的单词,但是行的结尾可能不同,需要删除整行。

示例:

这是txt文件中间的原始行:

.........
<br>rrrrr TTTTTT ffgggggggg
<br>ja UOOOOOOOO on >= 16 täysin.
<br>ja numeroyhdistelmä on 9- 39- 9
<br>ja href="./reeeee.html">wwwwjjhjhkkghjky. </a> </td>
</tr></TABLE>
<table border=0 cellpadding= 25 width= 560><TR><TD width=80></TD><TD 
width=240><PRE>
.........   
在python代码行之后

.........
<br>rrrrr TTTTTT ffgggggggg
<br>ja UOOOOOOOO on >= 16 täysin.
<br>ja href="./reeeee.html">wwwwjjhjhkkghjky. </a> </td>
</tr></TABLE>
<table border=0 cellpadding= 25 width= 560><TR><TD width=80></TD><TD 
width=240><PRE> 
.........

所以需要删除的内容是:

    <br>ja numeroyhdistelmä on 9- 39- 9

如果我在代码中使用字母“ä”,它会给出一些“unicode”错误,但我没有选择尝试其他单词来搜索,因为开始行也在其他地方,值“9-39-9”可能会改变。

这就是我的尝试:

f = open("text2.txt","r+")
d = f.readlines()
f.seek(0)
for line in d:
    if "numeroyhdistelmä" in line:
        f.write(line)
f.truncate()
f.close()

我认为字母“ä”不仅仅是问题,因为我正在测试此代码中的其他一些搜索词,并删除文本文件中的所有行。

谢谢!

3 个答案:

答案 0 :(得分:0)

我会读取行检查行,如果“要删除的单词存在”,则删除行,否则写入文件。

with open("file") as data:
    lines = data.readlines()

with open("file","w") as f:
    for line in lines:
        if "word to remove" in line:
            continue
        f.write(line,"\n")

答案 1 :(得分:0)

以下是我可以解决此问题的方法 - 此处还有一个关于使用with语法的问题,该语法在打开和关闭文件时首选:Why is with open() better for opening files in Python?

filename = 'text2.txt'
with open(filename, 'r+') as txt_file:
    temp = txt_file.readlines()
    txt_file.seek(0)

    for line in temp:
        if not 'numeroyhdistelm' in line:
            txt_file.write(line)

    txt_file.truncate()

答案 2 :(得分:0)

您现在只保存带有'numeroyhdistelmä'的行,您应该在循环中添加'not'。 使用@IBAction func googleSignIn(_ sender: Any) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } 然后with open()open()也是一种更好的做法。

close()

您收到编码错误,因为 test2.txt 文件不是 utf-8 编码的。如果您关心特殊字符,则应在打开文件时对其进行解码。 有wordFlag = 'numeroyhdistelmä' with open("text2.txt","r+") as f: lines = f.readlines() with open("text2.txt","w") as f: for line in f: if not wordFlag in line: f.write('line') f.truncate() encode()函数可用于字符串,但我更喜欢使用编解码器模块。我猜你的文件编码是拉丁语,但你应该检查它并根据需要更改变量。那么你的代码就像:

decode()
相关问题