我需要找到某个文本中出现的所有回文。我将从外部文件中提取数据。我需要注意数据的内存高效处理,因此我使用了 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)