1

so i am very very new to python. need some basic help.

my logic is to find words in text file.

party A %aapple 1
Party B %bat 2
Party C c 3

i need to find all the words starts from %.

my code is

 searchfile = open("text.txt", "r")
for line in searchfile:
 for char in line:
if "%" in char:
    print char      

searchfile.close()

but the output is only the % character. I need the putput to be %apple and %bat

any help?

2 Answers2

0

You are not reading the file properly.

searchfile = open("text.txt", "r")

lines = [line.strip() for line in searchfile.readlines()]
for line in lines:
    for word in line.split(" "):
        if word.startswith("%"):
            print word

searchfile.close()

You should also explore regex to solve this as well.

Bipul Jain
  • 4,523
  • 3
  • 23
  • 26
  • this is just printing the start letter. i need the whole word. like apple. not just an A – user3296651 Feb 12 '17 at 18:03
  • 1
    No it is not. What is your input. I am updating the answer to print the word including the % right now it apple , bat – Bipul Jain Feb 12 '17 at 18:05
  • I tested the script and it is working properly. But you are opening ```test.txt``` but @user3296651 wanted to open ```text.txt```. –  Feb 12 '17 at 18:08
  • its working now. thanks. can you share some link for basic python tutorial? – user3296651 Feb 12 '17 at 18:09
  • https://www.udacity.com/course/programming-foundations-with-python--ud036 –  Feb 12 '17 at 18:10
0

For the sake of exemplification, I'm following up on Bipul Jain's reccomendation of showing how this can be done with regex:

import re

with open('text.txt', 'r') as f:
    file = f.read()

re.findall(r'%\w+', file)

results:

['%apple', '%bat']
gregory
  • 10,969
  • 2
  • 30
  • 42