作为一个研究案例,我有一部由三个主要人物组成的文学小说,他们每个人都有自己的章节。也就是说:第一章是角色X(亚伦),第二章是角色Y(西格里厄斯),第三章是角色Z(乔尼),第四章是角色X,第五章是角色Y,第六章是角色Z,依此类推。。。我想数一数所有章节中关于字符X,字符Y和字符Z的字数
这是我目前正在处理的关于一个特定字符(亚伦)章节的Python代码:from itertools import islice
with open(textfile, 'rt', encoding='utf-8') as f:
# Computes the total word count of the file
text = f.read()
words = text.split()
wordCount = len(words)
print ("The total word count is:", wordCount)
# Aaron's chapters
chapterAaron1 = islice(f, 0, 123)
chapterAaron4 = islice(f, 223 ,326)
chapterAaron6 = islice(f, 639, 772)
chapterAaron10 = islice(f, 1125, 1249)
chapterAaron12 = islice(f, 1370, 1455)
chapterAaron15 = islice(f, 1657, 1717)
chapterAaron19 = islice(f, 2088, 2138)
chaptersAaron = (chapterAaron1, chapterAaron4, chapterAaron6, chapterAaron10, chapterAaron12, chapterAaron12, chapterAaron15, chapterAaron19)
# Computes the total word count of Aaron's chapters (does not work)
wordsAaron = chaptersAaron.split()
wordCountAaron = len(wordsAaron)
print ("The total word count of Aaron's chapters is:", wordCountAaron)
我已经手动决定了不同章节(每个字符)在txt文件的哪一行开始和结束。我使用islice将txt文件拆分为特定的章节(包含在特定的行号之间),以便计算这些行号(即章节)之间包含的字数。然而,我似乎找不到一种方法来以正确的方式实现islice的目的。我得到这个AttributeError:“tuple”对象没有属性“split”。我想要的是将一个特定字符的所有章节存储在一个变量中(例如chaptersAaron),这样我就可以用它来做一些事情,例如计算单词的总数并搜索其中特定单词的出现情况。在有人对我正确使用islice有什么建议吗?也很欢迎将文本拆分成章节。在