Fetch particular text from another file (python)
<p>I have a file of the following pattern:</p>

<pre><code>"abcd.asxs." "alphabets"
"wedf.345.po&amp;%12." "numbers"
"xyhd.iu*u." "characters"
"megaten4.koryaku-memo.xyz." "alphabets"
"adwdbk.uyequ." "alphabets"
"233432.2321." "numbers"
"tytqyw.sdfhgwq." "alphabets"
</code></pre>

<p>I want something like:</p>

<pre><code>string[0]=abcd.asxs
string[1]=megaten4.koryaku-memo.xyz
string[2]=tytqyw.sdfhgwq
and so on....
</code></pre>

<p>What code I have written is:</p>

<pre><code> #!/usr/bin/python

 import re

 important = []
 needed_categories = ["alphabets"]

 with open('file.txt') as fp:
        rec=fp.readlines()

 for line in rec:
        for category in needed_categories:
                if category in line:
                        important.append(line)
                        break
 print("\n".join(important))
</code></pre>

<p>Output I get:</p>

<p>"abcd.asxs." "alphabets"</p>

<p>"megaten4.koryaku-memo.xy." "alphabets"</p>

<p>"tytqyw.sdfhgwq." "alphabets"</p>

<p><strong>Points for your code:</strong></p>

<ul>
<li>You can iterate line by line using file handle directly. No need to save file data using <code>fp.readlines()</code> in list and then iterating.</li>
<li>Once needed_category is found, you are directly appending complete line. That's why you are getting wrong output. You need to split line and save first element only.</li>
<li>Didn't understand why you used <code>break</code>.</li>
</ul>

<p><strong>Working Code :</strong></p>

<pre><code>important = []
needed_categories = ["alphabets"]

with open('a.txt') as fp:
    for line in fp:
        temp = []
        for category in needed_categories:
            if category in line:
                temp = line.split()
                important.append(temp[0].replace('"','').strip("."))
print((important)
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py
['abcd.asxs', 'megaten4.koryaku-memo.xyz', 'adwdbk.uyequ', 'tytqyw.sdfhgwq']

C:\Users\dinesh_pundkar\Desktop&gt;
</code></pre>

python