假设我有一个充满昵称的文本文件。如何使用Python从这个文件中删除特定的昵称?


当前回答

在第一次传递中读取行并在第二次传递中进行更改(删除特定行)的问题是,如果文件大小很大,则会耗尽RAM。相反,更好的方法是逐行读取,并将它们写入单独的文件,删除不需要的文件。我曾经在12- 50gb大的文件上运行过这种方法,RAM使用几乎保持不变。只有CPU周期显示正在进行的处理。

其他回答

您可以使用re库

假设您能够加载完整的txt文件。然后定义一个不需要的昵称列表,然后用空字符串“”替换它们。

# Delete unwanted characters
import re

# Read, then decode for py2 compat.
path_to_file = 'data/nicknames.txt'
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')

# Define unwanted nicknames and substitute them
unwanted_nickname_list = ['SourDough']
text = re.sub("|".join(unwanted_nickname_list), "", text)

解决这个问题的方法只有一个:

with open("target.txt", "r+") as f:
    d = f.readlines()
    f.seek(0)
    for i in d:
        if i != "line you want to remove...":
            f.write(i)
    f.truncate()

该解决方案以r/w模式(“r+”)打开文件,并使用seek重置f指针,然后截断以删除最后一次写入之后的所有内容。

一般来说,你不能;您必须重新编写整个文件(至少从更改点到末尾)。

在某些特定的情况下,你可以做得比这个更好

如果所有的数据元素都是相同的长度,并且没有特定的顺序,并且您知道要删除的数据元素的偏移量,那么您可以将最后一项复制到要删除的数据元素之上,并在最后一项之前截断文件;

或者你可以用“这是坏数据,跳过它”的值覆盖数据块,或者在保存的数据元素中保留“此项已删除”的标记,这样你就可以在不修改文件的情况下标记它已删除。

对于短文档(小于100 KB的文档?)来说,这可能有点过分了。

按行号删除文件中的某一行。

用文件名和要删除的行号替换变量filename和line_to_delete。

filename = 'foo.txt'
line_to_delete = 3
initial_line = 1
file_lines = {}

with open(filename) as f:
    content = f.readlines() 

for line in content:
    file_lines[initial_line] = line.strip()
    initial_line += 1

f = open(filename, "w")
for line_number, line_content in file_lines.items():
    if line_number != line_to_delete:
        f.write('{}\n'.format(line_content))

f.close()
print('Deleted line: {}'.format(line_to_delete))

示例输出:

Deleted line: 3

我喜欢这个使用fileinput和inplace方法的方法:

import fileinput
for line in fileinput.input(fname, inplace =1):
    line = line.strip()
    if not 'UnwantedWord' in line:
        print(line)

它比其他答案少一点啰嗦而且足够快