Python : with dictionary, search for strings in another text file and print the entire line -
Python : with dictionary, search for strings in another text file and print the entire line -
i want search dictionary if 1 of words in sec txt file. have problem next code:
print 'searching known strings...\n' open('something.txt') f: haystack = f.read() open('d:\\users\\something\\desktop\\something\\dictionary\\entirelist.txt') f: needle in (line.strip() line in f): if needle in haystack: print line
the open statements not me, took them from: python: search strings listed in 1 file text file? want print line wrote line instead of needle. problems comes : says "line not defined".
my final objective see if words dictionary in "something.txt", , if yes, print line word identified. sorry bad english language or bad salutations, hope you'll help me! thx understanding :)
the specific exception asked because line
doesn't exist outside generator expression. if want access it, need maintain in same scope print
statement, this:
for line in f: needle = line.strip() if needle in haystack: print line
but isn't going particularly useful. it's going word needle
plus newline @ end. if want print out line (or lines?) haystack
include needle
, have search line, not inquire whether needle
appears anywhere in whole haystack
.
to literally you're asking for, you're going need loop on lines of haystack
, check each 1 needle
. this:
with open('something.txt') f: haystacks = list(f) open('d:\\users\\something\\desktop\\something\\dictionary\\entirelist.txt') f: line in f: needle = line.strip() haystack in haystacks: if needle in haystack: print haystack
however, there's neat trick may want consider: if can write regular look matches finish line includes needle
, need print out matches. this:
with open('something.txt') f: haystack = f.read() open('d:\\users\\something\\desktop\\something\\dictionary\\entirelist.txt') f: line in f: needle = line.strip() pattern = '^.*{}.*$'.format(re.escape(needle)) match in re.finditer(pattern, haystack, re.multiline): print match.group(0)
here's illustration of how regular look works:
^.*falco.*$
debuggex demo
of course of study if want search case-insensitively, or search finish words, etc., you'll need create minor changes; see regular look howto, or third-party tutorial, more.
python
Comments
Post a Comment