Ignore case in Python script [duplicate] - python

This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Case insensitive dictionary search? [duplicate]
(6 answers)
Closed 12 months ago.
In my Python script, I'm working with JSON files but in some files I have an input "racecards" and in some files I have "raceCards".
How can I ask to Python to use the two cases?
My script:
for file1 in FILE:
with open(path + '%s' %file1,encoding='utf-8') as f1:
INPUT1 = json.load(f1)
DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"]
X = list(DATA.values())
for x in X[0]:
ENTRY = []
for h1 in header1.split(','):
ENTRY.append(x[h1])
Entry = [str(i) for i in ENTRY]
towrite = ','.join(Entry)
print(towrite,file=output1)

One way is that you can simply use a try & except to implement it.
instead of:
DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"]
Replace with:
try:
DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"]
except Exception ignored:
DATA = INPUT1["pageProps"]["initialState"]["racecards"]["races"]

Related

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 create files on Windows with content coming from Python arrays? [duplicate]

This question already has answers here:
How to iterate over two arrays in parallel? [duplicate]
(4 answers)
Correct way to write line to file?
(17 answers)
print variable and a string in python
(6 answers)
Closed 2 years ago.
I have a bunch of Python arrays such as;
fileNameArray = ['fileName1', 'fileName2', 'fileName3']
titleArray = ['aTitle', 'bTitle', 'cTitle']
tagArray = ['abc', 'def', 'ghi', 'jkl', 'mno']
So, when I run the program, the output should be three files with names 'fileName1.mdx', 'fileName2.mdx', 'fileName3.mdx' with its content looking like;
---
title: 'aTitle'
Date Added: '2020-11-11'
summary: 'xyz.'
image: '/static/images/123.png'
tags: 'abc, def, ghi, jkl, mno'
---
When I run the program, how do I create a file named fileNamex.mdx with names coming from the fileNameArray, and its contents like title tag coming from the titleArray and tag key values coming from the tagArray.
Other keys like summary and image are static, that is the same values shown in the example should be on all files.
So, basically, how do I create files in Python (On Windows) and populate them with the initial content shown above?
Something like this?
for file, title in zip(fileNameArray, titleArray):
with open(file + '.mdx', 'w') as handle:
for line in (
"---", "title: '" + title + "'",
"summary: 'xyz'", "image: ''/static/images/123.png'",
"tags: '" + ", ".join(tagArray) + "'", "---"):
handle.write(line + '\n')
Stylistically f"title: '{title}'" would arguably be more elegant, but then an f-string would be rather unreadable and bewildering for the "tags: ..." case, so I went with simple string concatenation throughout. A third option is to use the legacy string formatting "title: '%s'" % (title) etc.

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'}

how to get two list concanate in one in python [duplicate]

This question already has answers here:
For loop and zip in python
(5 answers)
How do I iterate through two lists in parallel?
(8 answers)
Closed 3 years ago.
hello I would like to get two list in one
I have one list of name and one other of number in string i would like to say :
for i,j in map(None,[school,phonenumber]):
phrase = "{} : {}".format(i,j)
complete.append(phrase)
school and phonenumber are the list but I don't understand how to do for get the index of each line
import csv
import pandas as pd
f = open('phone.csv')
phonenumber = list(csv.reader(f))
f = open("school2.csv", "r")
school = list(csv.reader(f))
complete = []
for i,j in map(None,[school,phonenumber]):
phrase = "{} : {}".format(i,j)
complete.append(phrase)
print(complete)
I have tried that and I don't know where it's wrong
I would like just school : phonenumber ....
Thank you for your help !
Try this,
You need zip.
for i,j in zip(school,phonenumber):
phrase = "{} : {}".format(i,j)
complete.append(phrase)
zip is what you are looking for
for i,j in zip(school,phonenumber):

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

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()

Categories

Resources