Python 如何将枚举中的值与关键字匹配?
我想在上下文脚本中编写一个关键字,在这个脚本中,我首先读取一个文本文件作为枚举列表,然后返回一个给定的关键字和接下来的五个单词 我看到对C#也提出了类似的问题,我在Python中找到了Python 如何将枚举中的值与关键字匹配?,python,enumeration,Python,Enumeration,我想在上下文脚本中编写一个关键字,在这个脚本中,我首先读取一个文本文件作为枚举列表,然后返回一个给定的关键字和接下来的五个单词 我看到对C#也提出了类似的问题,我在Python中找到了enum模块的解决方案,但我希望有一个解决方案可以只使用enumerate()函数 到目前为止,我得到的是: # Find keywords in context import string # open input txt file from local path with open('C:\\Users\
enum
模块的解决方案,但我希望有一个解决方案可以只使用enumerate()
函数
到目前为止,我得到的是:
# Find keywords in context
import string
# open input txt file from local path
with open('C:\\Users\\somefile.txt', 'r', encoding='utf-8', errors='ignore') as f: # open file
data1=f.read() # read content of file as string
data2=data1.translate(str.maketrans('', '', string.punctuation)).lower() # remove punctuation
data3=" ".join(data2.split()) # remove additional whitespace from text
indata=list(data3.split()) # convert string to list
print(indata[:4])
searchterms=["text", "book", "history"]
def wordsafter(keyword, source):
for i, val in enumerate(source):
if val == keyword: # cannot access the enumeration value here
return str(source[i+5]) # intend to show searchterm and subsequent five words
else:
continue
for s in searchterms: # iterate through searchterms
print(s)
wordsafter(s, indata)
print("done")
我希望我可以像这里一样简单地访问枚举值,但事实似乎并非如此。由于@jasonharper的功劳,您的改进代码:
import string
def wordsafter(keyword, source):
for i, val in enumerate(source):
if val == keyword:
return ' '.join(source[i:i + 5]) # intend to show searchterm and subsequent five words
# wordsafter() for all instances
def wordsafter(keyword, source):
instances = []
for i, val in enumerate(source):
if val == keyword:
instances.append(' '.join(source[i:i + 5]))
return instances
# open input txt file from local path
with open('README.md', 'r', encoding='utf-8', errors='ignore') as f: # open file
data1 = f.read() # read content of file as string
data2 = data1.translate(str.maketrans('', '', string.punctuation)).lower() # remove punctuation
data3 = " ".join(data2.split()) # remove additional whitespace from text
indata = list(data3.split()) # convert string to list
searchterms = ["this", "book", "history"]
for string in searchterms: # iterate through searchterms
result = wordsafter(string, indata)
if result:
print(result)
source[i+5]
是列表中的一个元素,在当前迭代的元素之后是五个元素,如果剩余元素少于五个,则将失败。您需要一个切片,类似于source[i:i+5]
,以返回多个元素。非常感谢@jasonharper和Xander,修复了它。我一定是运气不好,从来没有剩下五个元素,所以我没有得到任何结果,只是在错误的地方寻找错误。当我分享脚本时,我会感谢你们两个。PS:我更新了脚本,在txt文件中查找上下文中的所有关键字实例,因为这个脚本只捕获第一个。有趣的是,我称之为“个人结果看起来很棒”。。。但显示整个输出超出了我的Jupyter笔记本所能处理的范围。将结果写入文件会产生58MB的数据。我想我需要解决一个循环问题。完成后,我将在另一个答案中共享脚本。@一旦我添加了一个函数,我就编辑了代码。我还没有测试过它,但我毫不怀疑它会起作用。祝你好运!