gpt4 book ai didi

python - 如何 grep 查找 unicode 字符?

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:11 25 4
gpt4 key购买 nike

如何使用 grep 搜索文件中的 unicode 字符字符串?

我正在尝试计算字符串“\xfe\n\xfe”出现的次数。我可以通过以下方式使用 Python 找到它:

open(filename).read().count('\xfe\n\xfe')

这会找到几千个匹配项。

但是,由于这会将整个文件加载到内存中,因此如果我尝试搜索大于系统内存的文件,则会崩溃。

所以我尝试通过 grep 做同样的事情:

grep -P -c "\xfe\n\xfe" filename

它消耗几乎 0 内存,这很棒,但即使我在同一个文件上运行它,它也找到 0 个匹配项。我的语法有什么问题吗?

最佳答案

您不需要将整个文件读入内存。您可以迭代该文件并计算该字符串在每一行中的出现次数(每次使用一对行):

count = 0
with open(filename) as f:
prev_line = next(f)
for line in f:
if prev_line.endswith('\xfe\n') and line.startswith('\xfe'):
count += 1
prev_line = line

关于python - 如何 grep 查找 unicode 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com