如何将枚举中的值与关键字匹配? [英] How to match value in enumeration to a keyword?

查看:67
本文介绍了如何将枚举中的值与关键字匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个上下文关键字脚本,在该脚本中,我首先读取一个文本文件作为枚举列表,然后返回给定的关键字和接下来的五个单词.

I want to write a keyword-in-context script in which I first read a text file as an enumerated list and then return a given keyword and the five next words.

我看到对C#提出了类似的问题,并且在Python中找到了 enum 模块的解决方案,但我希望有一个仅使用 enumerate()功能.

I saw that similar questions were asked for C# and I found solutions for the enum module in Python, but I hope there is a solution for just using the enumerate() function.

这是我到目前为止所得到的:

This is what I have got so far:

# 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")

我希望我可以像在这里那样简单地获取枚举的值,但事实并非如此.

I was hoping I could simply access the value of the enumeration like I did here, but that does not seem to be the case.

推荐答案

对@jasonharper表示感谢,您可以改善代码:

With credits to @jasonharper, your improved code:

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)

这篇关于如何将枚举中的值与关键字匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆