简体   繁体   中英

python print all words from list of a line

I am trying to code and print all keywords on a line from a list.I mean: i have a list keywords=['bike','car','home'] i have a text file:

every one has bike and car
i have a bike
i am trying to get a car and home

Coding:

keywords=['bike','car','home']
with open('qwe.txt','r') as file:
    for line in file:            
        for key in keywords:
            if key in line:
               a = key
               break
            else:
                a = 'nil'
        print a

my output prints only one key not all key present over list! I mean my output expected is:

bike car
bike
car home

Instead ,i get now as:

bike
bike
car

How can i print all the keys from the lines?Please help! Answers will be appreciated!

You have two separate problems here, both of which need to be fixed.

First, as pointed out by @jonrsharpe, you break as soon as you find the first match, which means you're specifically telling Python to stop after the first match, so it's doing exactly what you ask. Just remove that break .

Second, as pointed out by @hasan, even without the break , for each key, you're replacing a , either with the new key, or with nil . So, you're just going to print out either home or nil every time. What you want to do is accumulate all of the matching keys. Like this:

matches = []
for key in keywords:
    if key in line:
        matches.append(key)
if matches:
    print ' '.join(matches)
else:
    print 'nil'

From your comment:

small problem,if i have new line as 'car and bike',then its first printing 'bike car' instead of 'car bike'!

Think about what you're asking Python to do: You're going through the keys in keywords , and checking whether each one is found in line . So of course the order in which they're found will be the order they appear in keywords .

If you want them in the order they appear in the line instead, there are two options.

First, you can search through the line , looking for matches in keywords , instead of searching for keywords , looking for matches in line . If you only want to match complete words, and want duplicates to show up multiple times, this is dead simple:

for word in line.split():
    if word in keywords:
        matches.append(word)

If you want to match partial words (eg, your existing code finds car in "this program is designed for scaring small children" , but the code I just gave will not), you can search all substrings instead of all words:

for i in range(len(line)):
    for key in keywords:
        if line[i:].startswith(key):
            matches.append(key)

If you only want to find each word once, you can check if word not in matches before appending it.

And so on. Whatever you want to add, you have to think through what the rule is before you can turn it into code, but usually it won't be very hard.

If you don't mind the order, you can make your keywords a set and search the intersection with the set of words in line :

keywords = set(['bike','car','home'])
with open('qwe.txt', 'r') as file:
    for line in file:
        print ' '.join(keywords & set(line.split())) or 'nil'

This is faster when your lines and keywords are big, since you don't have to iterate over the lists.


Example

input

every one has bike and car
i have a bike
i am trying to get a car and home
i don't have any

output

car bike
bike
car home
nil

You're assigning a to new keyword each time, rather than storing each one you see. Maybe make a new list each time you look at a new line and append the words you find:

keywords=['bike','car','home']
with open('qwe.txt','r') as file:
    for line in file:
        a = []
        for key in keywords:
            if key in line:
               a.append(key)
        if len(a) > 0:
            print ' '.join(a)

You might also see if a list comprehension can build that array for you in a single line. Haven't tried it but it might be possible. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM