Add apostrophes to string to make it a certain length python [duplicate] - python

This question already has answers here:
How can I fill out a Python string with spaces?
(14 answers)
Closed 2 years ago.
I am writing a file which gets information about stock items from a csv, the issue is that most of the stock item IDs are 4 digits long, but some of them are 2 or 3 digits, and the remaining digits are replaced with apostrophes ( 872' or 99'' for example). Because the user can pass in specific stock item IDs it would be better if they did not have to include apostrophes in their input just so the code runs, so I want to append apostrophes to their input ID.
At the moment, the stock item IDs to get information for are retrieved using this code::
if args.ID:
if args.ID[0].endswith('.txt'):
with open(args.ID[0], 'r') as f:
IDs = [line for line in f]
else:
IDs = args.FTID
else:
IDs = [ID[25:29] for ID in df['Stock Items'].unique()]
Then I iterate through the dataframe:
for index, row in df.iterrows():
if row['Stock Items'][25:29] in FTIDs:
# Processing
I need to be able to make sure that any input IDs are in the format above.

If you have str and you are 100% sure it is not longer than 4, you can use .ljust to get str with required number of ' added following way
myid = "99"
formatted_id = myid.ljust(4, "'")
print(formatted_id)
Output:
99''

Related

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

Problems with using a for loop with a string from a text file to locate an index in a list of lists

I have a text file with a string that has a letter (beginning with "A" that is assigned to a random country). I import that line from the text file to be used with my code where I have a list of countries and rates. I strip the string so that I am left with the country and then I want to be able to locate the country in the string on a list of list that I created. The problem is that when I run my for loop to find the name of the country in the string in the list of lists, where each junior list has the name of the country, GDP and a rate, the for loop runs and can't find the country in the string, even though they are the same type and same spelling. Let me post my code and output below.
When I created the txt file or csv file, this is what I used:
f = open("otrasvariables2020.txt", "w")
f.write(str(mis_letras_paises) + "\n")
f.write(str(mis_paises) + "\n") #(This is the string I need)
f.write(str(mis_poblaciones) + "\n")
f.close() #to be ready to use it later
Let me post some of the output.
import linecache
with open("otrasvariables2020.txt") as otras_variables:
mis_paises = (linecache.getline("otrasvariables2020.txt",2))
#Here I get the line of text I need, I clean the string and create a
#list with 5 countries.
lista_mis_paises = mis_paises.translate({ord(i): None for i \
in "[]-\'"}).split(", ")
for i in lista_mis_paises:
if "\n" in i:
print(i)
i.replace("\n", "")
for i in lista_mis_paises:
if len(i) <= 2:
lista_mis_paises.pop(lista_mis_paises.index(i))
Final part of the question: So, ultimately what I want is to find in the array the junior list of the country in the list/string I imported from the text file. Once I locate that junior list I can use the rates and other values there for calculations I need to do. Any ideas what's wrong? The outcome should be the following: Afganistán and other 4 countries should be found in the list of lists, which, for Afganistán, happens to be the 1st item, so I should now be able to create another list of lists but with just the 5 countries instead of the 185 countries I began with.
If the concern you have is to strip special characters you don't want to use, I'll do something like that:
countries = linecache.getline("otrasvariables2020.txt",2).strip('[]-\'"').rstrip('\n').split(', ')
Note: with open("otrasvariables2020.txt") as otras_variables: is not used in the code you shared above, so can be removed.
Hope it helps.

How to convert list to 20 column array [duplicate]

This question already has answers here:
How to read a text file into a list or an array with Python
(6 answers)
Closed 3 years ago.
I am making a program that takes a text file that looks something like this:
1
0
1
1
1
and converts it into a list:
['1','0','1','1','1']
The file has 400 lines so I want to convert it into an array that's 20 columns by 20 rows.
just use slicing to chunk it every 20 entries:
lines = [*range(1,401)]
rows_cols = [lines[i:i + 20] for i in range(0, len(lines), 20)]
Detect characters one by one counting at the same time how many characters you detected. There are two cases one when you detect the character and the counter is less than 20 and the other one when you detect the newline character for which you don't update the counter. Therefore in the first case the detected character should be assigned to the list(updating at the same time the column variable) while on the other case you just skip the newline and you continue with the next character of the text file if the counter is less than 20. In case the counter is 20 you just simply update the variable which represents the lines of the list.
this is save the character in 20 column, if in case no of rows are not multple of 20, it will create a list less element than 20 and add it in main list
solu =[]
leng = 20
with open('result.txt','r') as f:
sol = f.readlines()
tmp = []
for i in sol:
if len(tmp)<leng:
tmp.append(i.strip('\n'))
else:
print(tmp)
solu.append(tmp)
tmp=[]
solu.append(tmp)
print(solu)

Remove strings before certain character batch/python [duplicate]

This question already has answers here:
How to get a string after a specific substring?
(9 answers)
Closed 5 years ago.
How can I remove letters before certain character? I need to remove every letter from following string until “[“ character and redirect output to .csv file.
{"__metadata": {"uri": loremipsum etc [ {rest of the document}
As per your provided info and required fields, i will suggest that if your JSON data is in a file then you can use:
import json
data = {}
with open("path to json file") as f:
data = json.loads(f.read())
or if your data is stored in string then you can simply do
data = json.loads("json data string")
now you have data in a python dictionary object. now you can easily get any field from the object e.g getting field "cuid" from the first object in entries list:
print data["entries"][0]["cuid"]
or alternatively you can loop on entries list and get all the fields you need e.g
for entry in data["entries"]:
print entry["cuid"]
print entry["name"]
print entry["id"]
print entry["type"]
Find the position of '[' and get the string after that position
print s[s.find("[")+1:].strip()
Sample output:
{rest of the document}
Hope it helps!
You can split from the first occurence and take the rest like :
>>> string = "Egg[spam:miam"
>>> string.split("[", 1)[1]
>>> spam:miam
OR
>>> string = "Egg[spam:miam"
>>> string[string.index("[") + 1:]
>>> spam:miam

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