python - 此代码段中是否正确使用了 memoryview 对象?
问题描述
我需要找到某个文本中出现的所有回文。我将从外部文件中提取数据。我需要注意数据的内存高效处理,因此我使用了 memoryview 对象。但是,我需要对 memoryview 对象执行一些字符串操作,所以我使用了 tobytes() 方法。这是在不复制数据的情况下处理这些对象的正确方法吗?
from collections import Counter
palindrome = []
# read file as binary data
with open('some_text.txt', 'rb') as fr:
# create memoryview object
data = memoryview(fr.read())
# applying the tobytes() method
text = data.tobytes()
# split the sentences to words
for word in text.split():
# append to palindrome list if true
if is_palindome(word):
palindrome.append(word)
# return a Counter object with the palindromes and the number of occurences
palindrome = Counter(palindrome)
print(palindrome)
解决方案
您可以只使用bytes
fromfr.read()
with open('some_text.txt', 'rb') as f:
b = f.read()
print(b.__class__, id(b), len(b))
data = memoryview(b)
text = data.tobytes()
print(text.__class__, id(text), len(text))
可能的输出:
<class 'bytes'> 47642448 173227
<class 'bytes'> 47815728 173227
对于 CPython ,id()
返回内存中对象的地址。所以data.tobytes()
在这种情况下返回一个副本。
考虑使用文本模式
with open('some_text.txt', 'r') as f:
推荐阅读
- javascript - 在 Jest 中编写测试时 Ref 为空
- laravel - 我如何返回多个页面的值.. 在 laravel 中我在下面给出的代码
- javascript - SQL - 如何获取单元格的特定值并将其保存到变量中?
- angular - 为什么我得到属性“地图”未定义
- java - 当整行为空时如何不将数据放入地图中
- c# - 不应为空的 C# 变量引发空引用异常
- oracle - 如何获取必填字段中的数据?
- python - 如何加快对 python 数组的操作?
- vbscript - 计算行数
- microsoft-graph-api - Microsoft Graph 中的用户主体名称 (UPN) 或邮件所有权验证