423,851 Members | 2,680 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,851 IT Pros & Developers. It's quick & easy.

Check of two words are present in text file or not. Python script

P: 1
The two words should be present or none should be present in text file. User should input two words and that word should be check into the text file be it any type such as .html,.txt,.doc,.php using python.
2 Weeks Ago #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 946
One of the answers give in the internet seems to be correct, so I will try to show hoe you can test this yourself.

Create some textfile (I will name it 'example.txt'), with the following content:
Expand|Select|Wrap|Line Numbers
  1. bla
  2. bla
  3. ble
  4. blu
  5. blo
  6. bla
The example says to do this to find 1 occurrence of your search text:
Expand|Select|Wrap|Line Numbers
  1. if 'bla' in open('example.txt').read():
  2.     print("true")
  3.  
This seems to work:
Expand|Select|Wrap|Line Numbers
  1. C:\temp>python
  2. ActivePython 3.5.3.3505 (ActiveState Software Inc.) based on
  3. Python 3.5.3 (default, May 16 2017, 01:12:46) [MSC v.1900 64 bit (AMD64)] on win32
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> if "bla" in open("example.txt").read():
  6. ...   print("true")
  7. ...
  8. true
  9. >>> if "blx" in open("example.txt").read():
  10. ...   print("true")
  11. ...
  12. >>>
  13.  
Let's first create a script with this example. Store the following in a text-file ame 'search.py'
Expand|Select|Wrap|Line Numbers
  1. if "bla" in open("example.txt").read():
  2.    print("true")
  3.  
and run: python search.py

you should get the result saying: true

Now, how to find if that word exists two (or more) times in example.txt?

Google for "find number of occurrences in a text in a string"
and change search.py to:
Expand|Select|Wrap|Line Numbers
  1. if "bla" in open("example.txt").read():
  2.    print("true")
  3.  
  4. a = open("example.txt").read()
  5. print(a.count("bla"))
  6.  
When typing: python search.py
The answer should be:
Expand|Select|Wrap|Line Numbers
  1. true
  2. 3
(providing you followed above instructions ;)

This should help you on your way to find the complete solution to your question.
2 Weeks Ago #2

Post your reply

Sign in to post your reply or Sign up for a free account.