user2820024
user2820024

Reputation: 49

How to detect keywords from text?

I am trying to make a script in Python to use at work to automate some of my tasks. I have been using the module pyautogui to simulate mouse clicks and keystrokes, and it has been working out great so far!

Right now I am trying to figure out how to automatically feed Python a few lines of text and detect some keywords. The text is going to be in the same place each time I run the script, so I figured I could use pyautogui to select the text I want and copy it to my clipboard. After that, I'd use the module win32clipboard to feed Python the text.

Python ends up just printing whatever is on my clipboard. What am I doing wrong? Is there an easier way?

import win32clipboard

win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
mytext = input(data)
keywords = ["m1", "M1", "Melding 1"]

if any(keyword in mytext for keyword in keywords):
     print("test")

input('Press ENTER to exit')

Upvotes: 1

Views: 1693

Answers (3)

DYZ
DYZ

Reputation: 57033

input(data) displays data and waits for your input (which later becomes the value of mytext). Simply remove that line. data is your text:

if any(keyword in data for keyword in keywords):
     print(keyword)

If your keywords did not have spaces, you could improve your program to avoid incidental substring matching and to get better performance by splitting the text into tokens and comparing the set of tokens to the set of keywords:

keywords = {"m1", "M1", "Melding_1"}
if keywords & set(data.split()):
     print("test")

Upvotes: 1

EchoCloud
EchoCloud

Reputation: 61

You're general problem is you're not parsing your text. It's coming in as one big block. You need to split it up into a word list so each word can be evaluated.

...
wordlist = mytext.split()

for trigger in keywords:
   if any(trigger in s for s in wordlist):
      print("HIT!")
...

Upvotes: 1

Abe
Abe

Reputation: 5508

You could replace:

if any(keyword in mytext for keyword in keywords):
     print("test")

with the longer and uglier (but functional!):

for word in mytext.split(' '):
    for keyword in keywords:
        if keyword == word: print word

Upvotes: 1

Related Questions