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


当前回答

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

其他回答

我喜欢下面解释的文件输入方法: 从文本文件中删除一行(python)

例如,我有一个文件,其中有空行,我想删除空行,这是我如何解决它:

import fileinput
import sys
for line_number, line in enumerate(fileinput.input('file1.txt', inplace=1)):
    if len(line) > 1:
            sys.stdout.write(line)

注意:在我的例子中,空行长度为1

如果您使用Linux,可以尝试以下方法。 假设你有一个名为animal.txt的文本文件:

$ cat animal.txt  
dog
pig
cat 
monkey         
elephant  

删除第一行:

>>> import subprocess
>>> subprocess.call(['sed','-i','/.*dog.*/d','animal.txt']) 

然后

$ cat animal.txt
pig
cat
monkey
elephant

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

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指针,然后截断以删除最后一次写入之后的所有内容。

您可以使用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)

也许你已经有了正确答案,但下面是我的答案。 我没有使用列表来收集未经过滤的数据(readlines()方法所做的),而是使用了两个文件。一个用于保存主数据,第二个用于在删除特定字符串时过滤数据。这是一个代码:

main_file = open('data_base.txt').read()    # your main dataBase file
filter_file = open('filter_base.txt', 'w')
filter_file.write(main_file)
filter_file.close()
main_file = open('data_base.txt', 'w')
for line in open('filter_base'):
    if 'your data to delete' not in line:    # remove a specific string
        main_file.write(line)                # put all strings back to your db except deleted
    else: pass
main_file.close()

希望你会发现这有用!:)