473,396 Members | 2,087 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Match 2 words in a line of file

Hi

Am pretty new to python and hence this question..

I have file with an output of a process. I need to search this file one
line at a time and my pattern is that I am looking for the lines that
has the word 'event' and the word 'new'.

Note that i need lines that has both the words only and not either one
of them..

how do i write a regexp for this.. or better yet shd i even be using
regexp or is there a better way to do this....

thanks

Jan 18 '07 #1
11 11792
el*********@gmail.com wrote:
Hi

Am pretty new to python and hence this question..

I have file with an output of a process. I need to search this file one
line at a time and my pattern is that I am looking for the lines that
has the word 'event' and the word 'new'.

Note that i need lines that has both the words only and not either one
of them..

how do i write a regexp for this.. or better yet shd i even be using
regexp or is there a better way to do this....

thanks
Maybe something like this would do:

import re

def lines_with_words(file, word1, word2):
"""Print all lines in file that have both words in it."""
for line in file:
if re.search(r"\b" + word1 + r"\b", line) and \
re.search(r"\b" + word2 + r"\b", line):
print line

Just call the function with a file object and two strings that
represent the words that you want to find in each line.

To match a word in regex you write "\bWORD\b".

I don't know if there is a better way of doing this, but I believe that
this should at least work.

Jan 19 '07 #2
Without using re, this may work (untested ;-):

def lines_with_words(file, word1, word2):
"""Print all lines in file that have both words in it."""
for line in file:
words = line.split()
if word1 in words and word2 in words:
print line
/Jean Brouwers
Rickard Lindberg wrote:
el*********@gmail.com wrote:
Hi

Am pretty new to python and hence this question..

I have file with an output of a process. I need to search this file one
line at a time and my pattern is that I am looking for the lines that
has the word 'event' and the word 'new'.

Note that i need lines that has both the words only and not either one
of them..

how do i write a regexp for this.. or better yet shd i even be using
regexp or is there a better way to do this....

thanks

Maybe something like this would do:

import re

def lines_with_words(file, word1, word2):
"""Print all lines in file that have both words in it."""
for line in file:
if re.search(r"\b" + word1 + r"\b", line) and \
re.search(r"\b" + word2 + r"\b", line):
print line

Just call the function with a file object and two strings that
represent the words that you want to find in each line.

To match a word in regex you write "\bWORD\b".

I don't know if there is a better way of doing this, but I believe that
this should at least work.
Jan 19 '07 #3
MrJean1 wrote:
def lines_with_words(file, word1, word2):
"""Print all lines in file that have both words in it."""
for line in file:
words = line.split()
if word1 in words and word2 in words:
print line
This sounds better, it's probably faster than the RE version, Python
2.5 has a really fast str.__contains__ method, done by effbot:

def lines_with_words(file, word1, word2):
"""Print all lines in file that have both words in it.
(word1 may be the less frequent word of the two)."""
for line in file:
if word1 in line and word2 in line:
print line

Bye,
bearophile

Jan 19 '07 #4
I see two potential problems with the non regex solutions.

1) Consider a line: "foo (bar)". When you split it you will only get
two strings, as split by default only splits the string on white space
characters. Thus "'bar' in words" will return false, even though bar is
a word in that line.

2) If you have a line something like this: "foobar hello" then "'foo'
in line" will return true, even though foo is not a word (it is part of
a word).

Jan 19 '07 #5

Rickard Lindberg wrote:
I see two potential problems with the non regex solutions.

1) Consider a line: "foo (bar)". When you split it you will only get
two strings, as split by default only splits the string on white space
characters. Thus "'bar' in words" will return false, even though bar is
a word in that line.

2) If you have a line something like this: "foobar hello" then "'foo'
in line" will return true, even though foo is not a word (it is part of
a word).
Here's a solution using re.split:

import re
import StringIO

wordsplit = re.compile('\W+').split
def matchlines(fh, w1, w2):
w1 = w1.lower()
w2 = w2.lower()
for line in fh:
words = [x.lower() for x in wordsplit(line)]
if w1 in words and w2 in words:
print line.rstrip()

test = """1st line of text (not matched)
2nd line of words (not matched)
3rd line (Word test) should match (case insensitivity)
4th line simple test of word's (matches)
5th line simple test of words not found (plural words)
6th line tests produce strange words (no match - plural)
7th line "word test" should find this
"""
matchlines(StringIO.StringIO(test), 'test', 'word')

Jan 19 '07 #6

Rickard Lindberg wrote:
I see two potential problems with the non regex solutions.

1) Consider a line: "foo (bar)". When you split it you will only get
two strings, as split by default only splits the string on white space
characters. Thus "'bar' in words" will return false, even though bar is
a word in that line.

2) If you have a line something like this: "foobar hello" then "'foo'
in line" will return true, even though foo is not a word (it is part of
a word).
Here's a solution using re.split:

import re
import StringIO

wordsplit = re.compile('\W+').split
def matchlines(fh, w1, w2):
w1 = w1.lower()
w2 = w2.lower()
for line in fh:
words = [x.lower() for x in wordsplit(line)]
if w1 in words and w2 in words:
print line.rstrip()

test = """1st line of text (not matched)
2nd line of words (not matched)
3rd line (Word test) should match (case insensitivity)
4th line simple test of word's (matches)
5th line simple test of words not found (plural words)
6th line tests produce strange words (no match - plural)
7th line "word test" should find this
"""
matchlines(StringIO.StringIO(test), 'test', 'word')

Jan 19 '07 #7
Rickard Lindberg, yesterday I was sleepy and my solution was wrong.
2) If you have a line something like this: "foobar hello" then "'foo'
in line" will return true, even though foo is not a word (it is part of
a word).
Right. Now I think the best solution is to use __contains__ (in) to
quickly find the lines that surely contains both substrings, then on
such possibly rare cases you can use a correctly done RE. If the words
are uncommon enough, such solution may be fast and reliable.
Using raw tests followed by slow and reliable ones on the rare positive
results of the first test is a solution commonly used in Computer
Science, that often is both fast and reliable. (It breaks when the
first test is passed too much often, or when it has some false
negatives).

Probably there are even faster solutions, scanning the whole text at
once instead of inside its lines, but the code becomes too much hairy
and probably it's not worth it.

Bye,
bearophile

Jan 19 '07 #8
On 18 Jan 2007 18:54:59 -0800, "Rickard Lindberg"
<ri******@student.liu.sewrote:
>I see two potential problems with the non regex solutions.

1) Consider a line: "foo (bar)". When you split it you will only get
two strings, as split by default only splits the string on white space
characters. Thus "'bar' in words" will return false, even though bar is
a word in that line.

2) If you have a line something like this: "foobar hello" then "'foo'
in line" will return true, even though foo is not a word (it is part of
a word).
1) Depends how you define a 'word'.

2) This can be resolved with

templine = ' ' + line + ' '
if ' ' + word1 + ' ' in templine and ' ' + word2 + ' ' in templine:
Dan
Jan 19 '07 #9
Daniel Klein wrote:
2) This can be resolved with

templine = ' ' + line + ' '
if ' ' + word1 + ' ' in templine and ' ' + word2 + ' ' in templine:
But then you will still have a problem to match the word "foo" in a
string like "bar (foo)".

Jan 20 '07 #10
On Fri, 19 Jan 2007 22:57:37 -0800, Rickard Lindberg wrote:
Daniel Klein wrote:
>2) This can be resolved with

templine = ' ' + line + ' '
if ' ' + word1 + ' ' in templine and ' ' + word2 + ' ' in templine:

But then you will still have a problem to match the word "foo" in a
string like "bar (foo)".
That's a good point for a general word-finder application, but in the case
of the Original Poster's problem, it depends on the data he is dealing
with and the consequences of errors.

If the consequences are serious, then he may need to take extra
precautions. But if the consequences are insignificant, then the fastest,
most reliable solution is probably a simple generator:

def find_new_events(text):
for line in text.splitlines():
line = line.lower() # remove this for case-sensitive matches
if "event" in line and "new" in line:
yield line

To get all the matching lines at once, use list(find_new_events(test)).

This is probably going to be significantly faster than a regex.

So that's three possible solutions:

(1) Use a quick non-regex matcher, and deal with false positives later;

(2) Use a slow potentially complicated regex; or

(3) Use a quick non-regex matcher to eliminate obvious non-matches, then
pass the results to a slow regex to eliminate any remaining false
positives.
Which is best will depend on the O.P.'s expected data. As always, resist
the temptation to guess which is faster, and instead use the timeit module
to measure it.
--
Steven.

Jan 20 '07 #11


egchow do i write a regexp for this.. or better yet shd i even be using
egcregexp or is there a better way to do this....
"A team of engineers were faced with a problem; they decided to handle
it with regular expressions. Now they had two problems"
Regular expressions are not always the best solution. Others have
pointed out how it can work with "if word in line", this approach will
do if you're dealing with simple cases.
Take a look at this discussion, it is very informative:
http://blogs.msdn.com/oldnewthing/ar...22/603788.aspx

Jan 20 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: bdwise | last post by:
I have this in my body tag: something();something(); document.thisForm.textBox1.focus();something(); And I want to find a part between the semicolons that ends in focus() and remove the...
0
by: Follower | last post by:
Hi, I am working on a function to return extracts from a text document with a specific phrase highlighted (i.e. display the context of the matched phrase). The requirements are: * Match...
2
by: cricfan | last post by:
I'm parsing a text file to extract word definitions. For example the input text file contains the following content: di.va.gate \'di_--v*-.ga_-t\ vb pas.sim \'pas-*m\ adv : here and there :...
6
by: Mark Findlay | last post by:
I am trying to figure out how to set up my reg exp search so that the search will only match on the exact word. Here is the current problem code: Word1 = "RealPlayer.exe" Word2 = "Player.exe"...
12
by: teoryn | last post by:
I've been spending today learning python and as an exercise I've ported a program I wrote in java that unscrambles a word. Before describing the problem, here's the code: *--beginning of file--*...
3
by: Hrvoje Niksic | last post by:
I often have the need to match multiple regexes against a single string, typically a line of input, like this: if (matchobj = re1.match(line)): ... re1 matched; do something with matchobj ......
2
by: Sejoro | last post by:
Hello, I am trying to write a program that opens a file; reads through it; outputs the text; then outputs the number of lines, words, and characters. Problem is, every time I try to compile, no...
2
by: Slippy27 | last post by:
I'm trying to modify a find/replace script which iterates through a file A and makes replacements defined in a csv file B. My original goal was to change any line in file A containing a search string...
25
by: joeferns79 | last post by:
I had posed a similar topic some time back but I want some additional information from the input file. The log file is as shown... - App Number: 0 - Response for AE Completion No such...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.