By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,668 Members | 1,552 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,668 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.
Nov 29 '18 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 1,035
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")
This seems to work:
Expand|Select|Wrap|Line Numbers
  1. C:\temp>python
  2. ActivePython (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. >>>
Let's first create a script with this example. Store the following in a text-file ame ''
Expand|Select|Wrap|Line Numbers
  1. if "bla" in open("example.txt").read():
  2.    print("true")
and run: python

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 to:
Expand|Select|Wrap|Line Numbers
  1. if "bla" in open("example.txt").read():
  2.    print("true")
  4. a = open("example.txt").read()
  5. print(a.count("bla"))
When typing: python
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.
Dec 1 '18 #2

Post your reply

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