Searching exact variable in a text file using python [duplicate] - python

This question already has answers here:
How can I match an exact word in a string?
(9 answers)
Closed 7 years ago.
I am trying to search exact variable in a file but not able to do so. I.e. if I search for 'akash' in a file then all lines that contain akash is returned, even if they contain only 'akashdeep' and not exact 'akash'.
__author__ = 'root'
def userinGroups(userName):
with open('/etc/group','r') as data:
associatedGroups=[]
for line in data:
if userName in line:
associatedGroups.append(line.split(':')[0])
return associatedGroups
print userinGroups('akash')
This function must only return lines containing 'akash' and not those containing 'akashdeep'.
I tried using re module but can not find any example where a variable has been searched.
I also tried:
for 'akash' in line.split(':')
But in this scenario if a line contains multiple group entries then this fails.

Hi Have found solution to my problem with help of all members who responded to this post.Here goes the final solution
__author__ = 'root'
import re
def findgroup(line,userName):
result=re.findall('\\b'+userName+'\\b',line)
if len(result)>0:
return True
else:
return False
def userinGroups(userName):
with open('/etc/group','r') as data:
associatedGroups=[]
for line in data:
if findgroup(line,userName):
associatedGroups.append(line.split(':')[0])
return associatedGroups
print userinGroups('akas')

Using regex you can use re.search:
def userinGroups(userName):
r = re.compile(r'\b{0}\b'.format(userName))
with open('/etc/group', 'r') as data:
return [line.split(":", 1)[0] for line in data if r.search(line)]
Or use subprocess to run the groups command:
from subprocess import check_output
def userinGroups(userName):
return check_output(["groups",userName]).split(":",1)[1].split()

Related

python re.match doesn't work for a multipleline text file

I would like to write a Python program that searches and saves the vocabulary definition of an English word.
I have converted a Babylon English-Italian dictionary into a text file.
I would like that re.match() matches the first word of each line, but it doesn't.
I get always: 'not found', namely None for any query (word copied in my code) I use.
The Babylon text file can be found here:
https://tempfile.io/en/ba2voaBnDJsn24P/file
Thanks
import clipboard
import json
import re
wordcopied = clipboard.paste()
print(wordcopied)
dictionary = {}
with open("/home/user/Babylon-EI.txt", "r") as source:
lsource = source.readlines()
for line in lsource:
#print(type(line))
matc = re.match(wordcopied, line, re.MULTILINE | re.DOTALL)
if matc != None:
print(line)
dictionary = {wordcopied:line}
else:
print('not found')
break
I've tried also with re.search, and with multiple flags..
Related questions are all answered regarding flags and blanks

Python replace string in loop for a text file [duplicate]

This question already has answers here:
Python: Replace multiple strings in text file with multiple inputs
(4 answers)
Closed 2 years ago.
I have been trying to modify a specific word in a text file, using a for loop. The word I wish to change in the Fe.in file is >latt_par. I would like to create one file for each value of vol in the list. However, I just keep getting the last one "3.05". Is there a way you can guide me please? I am starting in Python.
Here is my code
vols = [2.65, 2.85, 3.05]
temp = [100,200,300]
for x in vols:
f = open('Fe.in','r')
filedata = f.read()
f.close()
newvol = filedata.replace("latt_par", str(x))
f = open('Fe_' + str(x) +'.in','w')
f.write(newvol)
f.close()
I would also like to replace another string in the file Fe.in, which I want to run over the variable temp, but I have not been able to.
Any help is greatly appreciated!
with open('Fe.in','r') as msg:
data = msg.read()
for x in vols:
wdata = data.replace("latt_par", str(x))
with open('Fe_' + str(x) +'.in','w') as out_msg:
out_msg.write(wdata)
Like that you don't need to open your template N times, and the with method allows to not close the file with no troubles.

How to turn a text file into a python dictionary [duplicate]

This question already has answers here:
How to convert a file into a dictionary?
(11 answers)
Closed 2 years ago.
If I had a text file with the following texts:
string, float
string 2, float 2
string 3, float 3
... and so on
How would I turn this into a python dictionary?
Ultimately, I would like all of my strings to become the key and all of the floats to become the value.
I have tried turning this into a set, yet I was unable to get to where I wanted it to be.
I have also tried the following code, as I saw another post with a similar problem giving me this solution. Yet, I was unable to get it to print anything.
m={}
for line in file:
x = line.replace(",","") # remove comma if present
y=x.split(':') #split key and value
m[y[0]] = y[1]
Thank you so much.
If every line in the text file is formatted exactly as it is in the example, then this is what I would do:
m = {}
for line in file:
comma = line.find(", ") # returns the index of where the comma is
s = line[:comma]
f = line[comma+1:]
m[s] = str.strip(f) # str.strip() removes the extra spaces
You need to research more. Don't be lazy.
m = {}
for line in file:
(key, value) = line.split(',') # split into two parts
m[key] = value.strip('\n') # remove the line break and append to dictionary
# output
# {'string1': ' 10', 'string2': ' 11'}

Replace words in a text file with different words (python) [duplicate]

This question already has answers here:
variable not defined in python
(3 answers)
Closed 3 years ago.
I am trying to replace the words in a textfile with English words (kind of like a translator). However, I get the error builtins.NameError: name 'contents' is not defined. Incase you need to know, the textfile is a list of strings (in Chinese) separated by commas (to which I need to replace by English strings).
def translate():
contents = ""
deleteWords = ["hop", "job"]
replaceWords = {"T波改变": "T-wave", "窦性心律不齐":"sinus arrhythmia"}
with open("sample.txt") as diagnosis:
contents = diagnosis.read()
for key, value in replaceWords.iteritems():
contents = contents.replace(key, value)
return contents
print(contents)
You declare contents inside your function, so it is scoped to this function and can not be accessed outside of the function.
Try: print(translate()) instead of print(contents)
The contents is a private variable that is only available inside of the function and is up for recycling as soon as the function is done. You need to call the function and save its value.
def translate():
contents = ""
#deleteWords = ["hop", "job"] # This variable is unused so commented out. Delete this line
replaceWords = {"T波改变": "T-wave", "窦性心律不齐":"sinus arrhythmia"}
with open("sample.txt") as diagnosis:
contents = diagnosis.read()
for key, value in replaceWords.iteritems():
contents = contents.replace(key, value)
return contents
# Here contents is a different variable with the same value
contents = translate() # <== Added this line to make it work
print(contents)

Find the count of the words in the text file using python [duplicate]

This question already has answers here:
python - find the occurrence of the word in a file
(6 answers)
Closed 9 years ago.
I had text file named as content_data with the following content
A house is house that must be beautiful house and never regrets the regrets for the baloon in
the baloons. Find the words that must be the repeated words in the file of house and ballons
Now i need to read the file using python and need find the count of each and every word
We need to implement the result in the form of a dictionary like below format
{'house':4,'baloon':3,'in':4........},
i mean in the format of {word:count}
Can anyone please let me know how to do this
from collections import Counter
from string import punctuation
counter = Counter()
with open('/tmp/content_data') as f:
for line in f:
counter.update(word.strip(punctuation) for word in line.split())
result = dict(counter)
# note: because we have
# isinstance(counter, dict)
# you may as well leave the result as a Counter object
print result

Categories

Resources