-1

I'm working on a problem where I need to go through the items of a passage and identify the words that are "unknown". I have two lists.

The first (the passage): ["this","is","a","test","does","it","work"]

And a list of "known" words: ["this","is","a","test"]

I'm a pretty elementary coder in Python, so I'm trying to use nested for-loops, going through the items of the passage list checking them against the words in the "known" list, but I'm facing some problems.

for word in passage:
    for word1 in known:
        if word == word1:
            print word + " "
        else:
            print "* " + word + " * "   

The expected result would be >>>"this is a test * does * * it * * work *"

Throsby
  • 199
  • 1
  • 1
  • 6
  • What a problem You have? –  Apr 09 '16 at 21:46
  • 1
    python has a neat feature: `for word in known: if word in passage: ...` Then you can avoid the second `for` loop and the `==` – jDo Apr 09 '16 at 21:49

3 Answers3

1

Try this:

def identify(passage, known_words):
    result = [i if i in known_words else "* " + i + " *" for i in passage]
    return " ".join(result)

Result:

>>> identify(["this","is","a","test","does","it","work"], ["this","is","a","test"])
'this is a test * does * * it * * work *'
Kidus
  • 1,785
  • 2
  • 20
  • 36
1

I should make my comment an answer, I guess. Python has a neat feature; namely the keyword in that you're already using in the two for loops. in also allows you to search a list, tuple or dictionary for the existence of a variable, phrase, etc. without the use of an explicit forloop. So instead of:

for word in passage:
    for word1 in known:
       ...

You can simply write:

for word in passage:
    # here, python will search the entire list (known) for word
    if word in known:
        print word + " "
    else:
        print "* " + word + " * " 
zondo
  • 19,901
  • 8
  • 44
  • 83
jDo
  • 3,962
  • 1
  • 11
  • 30
0
passage = ['this','is','a','test','does','it','work']
known_words = ['this','is','a','test']
new_string = []
for word in passage:
    if word in known_words:
        new_string.append(word + " ")
    else:
        new_string.append("* " + word + " * ")

print ''.join(new_string)

output: this is a test * does * * it * * work *

n1c9
  • 2,662
  • 3
  • 32
  • 52