【发布时间】:2023-01-27 23:06:43
【问题描述】:
我有一个文件,其中逐行包含句子。我需要在特定单词(不区分大小写)之前得到 10 个单词,但它也可以在前一行中。例如:如果我想要单词 ball 并且它是第二行的第四位,那么我需要该行中的 3 个单词和前一行甚至之前的 7 个单词。我也想不出从前几行中准确获取 10 个单词的方法。这是我到目前为止所拥有的:
for line in file:
# reading each word
for words in line.split():
y = 'myword'.lower
if y = words.lower:
index = words.index(y)
i = 0, z = 0
for words in line[i]:
sentence += words
if str(len(sentence.split()) != 10:
i--
print(sentence)
【问题讨论】:
-
您需要跟踪句子边界吗?
-
当您尝试执行此代码时,
if y = words.lower:行没有错误? -
我强烈建议学习the official python tutorial 或其他一些课程,以更好地了解 python 语法。