1

I have a list of prepositions in a txt file. I am creating a function such that it will extract the word following the prepositions from a string. Since there are many prepositions , it would not be feasible to directly put them into re.compile . So i am using a txt file. Here's my code :

with open("Input.txt"):
words = "|".join(line.rstrip() for line in open)
pattern = re.compile('{}\s(\w+|\d+\w+)\s\w+'.format(words))

where {} would represent match of preps ,whereas \s is a space followed by a word or a combination of digits and words like 20th cross and so on. The error i'm getting is

TypeError                                 Traceback (most recent call last)
<ipython-input-43-0aed517ef1ba> in <module>()
  1 with open("Input.txt"):
----> 2     words = "|".join(line.rsplit() for line in open)
  3 pattern = re.compile("{}\s(\w+|\d+\w+)\s\w+".format(words))

TypeError: 'builtin_function_or_method' object is not iterable

The Input.txt file has contents as ['near','above','towards'...] and so on.. how do i iterate over it??

1 Answer 1

2

The code is iterating open function. You should interate the a file object to get lines.

And rsplit is seems like a typo of rstrip.

with open("Input.txt") as f:
    words = "|".join(line.rstrip() for line in f)
    pattern = re.compile(r'(?:{})\s(\w+|\d+\w+)\s\w+'.format(words))

In case word contains some character that has special meaning in regular expression, it should be escaped using re.escape.

with open("Input.txt") as f:
    words = "|".join(re.escape(line.rstrip()) for line in f)
    pattern = re.compile(r'(?:{})\s(\w+|\d+\w+)\s\w+'.format(words))
Sign up to request clarification or add additional context in comments.

4 Comments

i tried with re.search and it is extracting the wrong part . text3 = "coo1, renissance park one, near yeshwanthpur metro, near columbia asia hospital , on a road parallel to railway track." q = re.search(pattern,text3)
hi, thanks but i want only the words following near to get extracted(or along with it).. i just want near yeshwantpur metro or near columbia asia
@Sword, Could you post a separated question? (with content of the file, expected output, original text)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.