假设我有一个充满昵称的文本文件。如何使用Python从这个文件中删除特定的昵称?
当前回答
如果您使用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("yourfile.txt", "r") as file_input:
with open("newfile.txt", "w") as output:
for line in file_input:
if line.strip("\n") != "nickname_to_delete":
output.write(line)
就是这样!在一个且只有一个循环中,你可以做同样的事情。这样会快得多。
你想从文件中删除特定的行,所以使用这个简短的代码片段,你可以很容易地删除任何带有句子或前缀(符号)的行。
with open("file_name.txt", "r") as f:
lines = f.readlines()
with open("new_file.txt", "w") as new_f:
for line in lines:
if not line.startswith("write any sentence or symbol to remove line"):
new_f.write(line)
在第一次传递中读取行并在第二次传递中进行更改(删除特定行)的问题是,如果文件大小很大,则会耗尽RAM。相反,更好的方法是逐行读取,并将它们写入单独的文件,删除不需要的文件。我曾经在12- 50gb大的文件上运行过这种方法,RAM使用几乎保持不变。只有CPU周期显示正在进行的处理。
按行号删除文件中的某一行。
用文件名和要删除的行号替换变量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
您可以使用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)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录