Python 3.5, how to remove the brackets and quotes from an element when printing or sending the value to a function? - python-3.x

I am reading a list of states from a file into an list[]:
mystk = []
with open('state_list.txt') as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')
for row in readCSV:
mystk.append(row)
After the read I am adding the values in to a list.
print(str(mystk[0]).strip())
i=0
while i < 10:
strList = mystk[i]
print('Print:',strList)
i = i +1
The output of the above is :
Print: ['AL']
Print: ['AK']
Print: ['AZ']
Print: ['AR']
Print: ['CA']
Print: ['CO']
Print: ['CT']
Print: ['DE']
Print: ['FL']
Print: ['GA']
I am trying to achieve the following:
Print: AL
Print: AK
Print: AZ
Print: AR
Print: CA
Print: CO
Print: CT
Print: DE
Print: FL
Print: GA
I guess I could write a function or loop to strip out the ['?'] using regex or code like this:
i=0
while i < 10:
strList = mystk[i]
strList = str(strList).replace("['", "")
strList = strList.replace("']", "")
print(' ','Print:',strList)
i = i +1
However I was hoping there was an easier way then the code above however I am new to python and if this is the only way then it works for me.

this are recommendations that I mention in my comment plus some other
import csv
def getTID(file='TID.csv', delim='\n'):
result = []
with open(file) as csvTID:
readCSV = csv.reader(csvTID, delimiter=delim)
for row in readCSV:
result.append( row[0] )
return result
stockList = getTID()
for x in stockList:
print(x)
here with the use of arguments give the function more flexibility and with default values I retain the original behavior that way you don't need to modify your code (or the name of the file) if you want to use your function with another file like 'TID_2.cvs' for example, in that case just call getTID('TID_2.cvs') and as the function don't do anything to some global variable you can have the data from 2 or more different files in different variables if you need it, for example
stockList1 = getTID('TID_1.cvs')
stockList2 = getTID('TID_2.cvs')

every line of the csv file is split by commas, to get the string joined by commas again, use str.join:
sep = ", "
for row in mystk:
print(' ', 'Print:', sep.join(row))

Guys thank you all very much, learning this is stuff is awesome. So many ways to do stuff. After reading your comments and understanding the concepts I have written the following function to get the stock list I need:
import csv
stockList = []
def getTID():
with open('TID.csv') as csvTID:
readCSV = csv.reader(csvTID,delimiter='\n')
for row in readCSV:
stockList.append((row[0]))
getTID()
for x in stockList[:]: print(x)
This returns the list as expected: VOD.L, APPL, etc.

Related

How to get all but last element outside of loop in Python

I have two problems with this code.
I need to get the string list calibration_values out of the loop so I can use them elsewhere in the program.
I need all of the elements in the string list except the last one. I am not able to use pop because this is a string and not a list. I am unable to use variable[:-1] because that truncates the last number by one digit instead of giving me all but the last element in the list. I thought maybe I needed to get the values out of the function for [:-1] to work but that takes me back to issue #1.
What am I doing wrong here?
def Parse_CSV(file, string):
global cal_string
global calibration_values
cal_string = []
calibration_values = []
with open(file, "r") as csv_file:
reader = csv.reader(csv_file, delimiter=',')
reader2 = csv.DictReader(csv_file)
for row in reader:
for column in row:
if string in column:
# print("Found search string:", string, " in ", file," .Writing Calibration String\n")
cal_string = row
calibration_values = cal_string[1]
print(calibration_values)

How to split strings from .txt file into a list, sorted from A-Z without duplicates?

For instance, the .txt file includes 2 lines, separated by commas:
John, George, Tom
Mark, James, Tom,
Output should be:
[George, James, John, Mark, Tom]
The following will create the list and store each item as a string.
def test(path):
filename = path
with open(filename) as f:
f = f.read()
f_list = f.split('\n')
for i in f_list:
if i == '':
f_list.remove(i)
res1 = []
for i in f_list:
res1.append(i.split(', '))
res2 = []
for i in res1:
res2 += i
res3 = [i.strip(',') for i in res2]
for i in res3:
if res3.count(i) != 1:
res3.remove(i)
res3.sort()
return res3
print(test('location/of/file.txt'))
Output:
['George', 'James', 'John', 'Mark', 'Tom']
Your file opening is fine, although the 'r' is redundant since that's the default. You claim it's not, but it is. Read the documentation.
You have not described what task is so I have no idea what's going on there. I will assume that it is correct.
Rather than populating a list and doing a membership test on every iteration - which is O(n^2) in time - can you think of a different data structure that guarantees uniqueness? Google will be your friend here. Once you discover this data structure, you will not have to perform membership checks at all. You seem to be struggling with this concept; the answer is a set.
The input data format is not rigorously defined. Separators may be commas or commas with trailing spaces, and may appear (or not) at the end of the line. Consider making an appropriate regular expression and using its splitting feature to split individual lines, though normal splitting and stripping may be easier to start.
In the following example code, I've:
ignored task since you've said that that's fine;
separated actual parsing of file content from parsing of in-memory content to demonstrate the function without a file;
used a set comprehension to store unique results of all split lines; and
used a generator to sorted that drops empty strings.
from io import StringIO
from typing import TextIO, List
def parse(f: TextIO) -> List[str]:
words = {
word.strip()
for line in f
for word in line.split(',')
}
return sorted(
word for word in words if word != ''
)
def parse_file(filename: str) -> List[str]:
with open(filename) as f:
return parse(f)
def test():
f = StringIO('John, George , Tom\nMark, James, Tom, ')
words = parse(f)
assert words == [
'George', 'James', 'John', 'Mark', 'Tom',
]
f = StringIO(' Han Solo, Boba Fet \n')
words = parse(f)
assert words == [
'Boba Fet', 'Han Solo',
]
if __name__ == '__main__':
test()
I came up with a very simple solution if anyone will need:
lines = x.read().split()
lines.sort()
new_list = []
[new_list.append(word) for word in lines if word not in new_list]
return new_list
with open("text.txt", "r") as fl:
list_ = set()
for line in fl.readlines():
line = line.strip("\n")
line = line.split(",")
[list_.add(_) for _ in line if _ != '']
print(list_)
I think that you missed a comma after Jim in the first line.
You can avoid the use of a loop by using split property :
content=file.read()
my_list=content.split(",")
to delete the occurence in your list you can transform it to set :
my_list=list(set(my_list))
then you can sort it using sorted
so the finale code :
with open("file.txt", "r") as file :
content=file.read()
my_list=content.replace("\n","").replace(" ", "").split(",")
result=sorted(list(set(my_list)))
you can add a key to your sort function

How do I print without square brackets

so I got this function here, and what it's supposed to do is create a file, that I can write in. the second and third parameters are lists, while the first is just the file name that I am going to create to write in. In the function, I made a for loop, and I'm looping through the all_students_list, which is a list, but at each index, is also a list, with the first name and last name in the list. all_courses_list is a list of all the courses in the school, and Schedule is a list that another function returns, giving us the schedule of the student. Then I added the student name and the schedule together, to write to the file. The problem is that it also prints [] square brackets. How can I get rid of it? I've already tried to do
.replace('[', '')
.replace(']', '')
But it doesn't work.
Here is my code.
def generate_student_schedules(filename, all_courses_list, all_students_list):
with open(filename,'w') as fileout:
for one_student in all_students_list:
schedule = get_schedule(all_courses_list)
one_line = ''
one_line += (f'{one_student}')
one_line += (f'{schedule}\n')
fileout.write(one_line)
If one_student is an actual list, then you can use " ".join(one_student), so overall:
def generate_student_schedules(filename, all_courses_list, all_students_list):
with open(filename,'w') as fileout:
for one_student in all_students_list:
schedule = get_schedule(all_courses_list)
one_line = ''
one_line += (" ".join(one_student))
one_line += (f'{schedule}\n')
fileout.write(one_line)
When you print a list, Python's default is to print the brackets and items in the list. You have to build a single string of the components of the list and print that single string. Your format string can pull out individual items or use join across all the items if they are all strings:
>>> student = ['John','Smith']
>>> schedule = ['Class1','Class2']
>>> print(student,schedule)
['John', 'Smith'] ['Class1', 'Class2']
>>> line = f'{student[1]}, {student[0]}: {", ".join(schedule)}'
>>> print(line)
Smith, John: Class1, Class2

Read out .csv and hand results to a dictionary

I am learning some coding, and I am stuck with an error I can't explain. Basically I want to read out a .csv file with birth statistics from the US to figure out the most popular name in the time recorded.
My code looks like this:
# 0:Id, 1: Name, 2: Year, 3: Gender, 4: State, 5: Count
names = {} # initialise dict names
maximum = 0 # store for maximum
l = []
with open("Filepath", "r") as file:
for line in file:
l = line.strip().split(",")
try:
name = l[1]
if name in names:
names[name] = int(names[name]) + int(l(5))
else:
names[name] = int(l(5))
except:
continue
print(names)
max(names)
def max(values):
for i in values:
if names[i] > maximum:
names[i] = maximum
else:
continue
return(maximum)
print(maximum)
It seems like the dictionary does not take any values at all since the print command does not return anything. Where did I go wrong (incidentally, the filepath is correct, it takes a while to get the result since the .csv is quite big. So my assumption is that I somehow made a mistake writing into the dictionary, but I was staring at the code for a while now and I don't see it!)
A few suggestions to improve your code:
names = {} # initialise dict names
maximum = 0 # store for maximum
with open("Filepath", "r") as file:
for line in file:
l = line.strip().split(",")
names[name] = names.get(name, 0) + l[5]
maximum = [(v,k) for k,v in names]
maximum.sort(reversed=True)
print(maximum[0])
You will want to look into Python dictionaries and learn about get. It helps you accomplish the objective of making your names dictionary in less lines of codes (more Pythonic).
Also, you used def to generate a function but you never called that function. That is why it's not printing.
I propose the shorted code above. Ask if you have questions!
Figured it out.
I think there were a few flow issues: I called a function before defining it... is that an issue or is python okay with that?
Also I think I used max as a name for a variable, but there is a built-in function with the same name, that might cause an issue I guess?! Same with value
This is my final code:
names = {} # initialise dict names
l = []
def maxval(val):
maxname = max(val.items(), key=lambda x : x[1])
return maxname
with open("filepath", "r") as file:
for line in file:
l = line.strip().split(",")
name = l[1]
try:
names[name] = names.get(name, 0) + int(l[5])
except:
continue
#print(str(l))
#print(names)
print(maxval(names))

How do I print out results on a separate line after converting them from a set to a string?

I am currently trying to compare to text files, to see if they have any words in common in both files.
The text files are as
ENGLISH.TXT
circle
table
year
competition
FRENCH.TXT
bien
competition
merci
air
table
My current code is getting them to print, Ive removed all the unnessecary squirly brackets and so on, but I cant get them to print on different lines.
List = open("english.txt").readlines()
List2 = open("french.txt").readlines()
anb = set(List) & set(List2)
anb = str(anb)
anb = (str(anb)[1:-1])
anb = anb.replace("'","")
anb = anb.replace(",","")
anb = anb.replace('\\n',"")
print(anb)
The output is expected to separate both results onto new lines.
Currently Happening:
Competition Table
Expected:
Competition
Table
Thanks in advance!
- Xphoon
Hi I'd suggest you to try two things as a good practice:
1) Use "with" for opening files
with open('english.txt', 'r') as englishfile, open('french.txt', 'r') as frenchfile:
##your python operations for the file
2) Try to use the "f-String" opportunity if you're using Python 3:
print(f"Hello\nWorld!")
File read using "open()" vs "with open()"
This post explains very well why to use the "with" statement :)
And additionally to the f-strings if you want to print out variables do it like this:
print(f"{variable[index]}\n variable2[index2]}")
Should print out:
Hello and World! in seperate lines
Here is one solution including converting between sets and lists:
with open('english.txt', 'r') as englishfile, open('french.txt', 'r') as frenchfile:
english_words = englishfile.readlines()
english_words = [word.strip('\n') for word in english_words]
french_words = frenchfile.readlines()
french_words = [word.strip('\n') for word in french_words]
anb = set(english_words) & set(french_words)
anb_list = [item for item in anb]
for item in anb_list:
print(item)
Here is another solution by keeping the words in lists:
with open('english.txt', 'r') as englishfile, open('french.txt', 'r') as frenchfile:
english_words = englishfile.readlines()
english_words = [word.strip('\n') for word in english_words]
french_words = frenchfile.readlines()
french_words = [word.strip('\n') for word in french_words]
for english_word in english_words:
for french_word in french_words:
if english_word == french_word:
print(english_word)

Resources