Creating a function to concatenate strings based on len(array) - python

I am trying to concatenate a string to send a message via python>telegram
My plan is so that the function is modular.
It first import lines from a .txt file and based on that many lines it creates two different arrays
array1[] and array2[], array1 will receive the values of the list as strings and array2 will receive user generated information to complemente what is stored in the same position as to a way to identify the differences in the array1[pos], as to put in a way:
while (k<len(list)):
array2[k]= str(input(array1[k]+": "))
k+=1
I wanted to create a single string to send in a single message like however in a way that all my list goes inside the same string
string1 = array1[pos]+": "+array2[pos]+"\n"
I have tried using while to compared the len but I kept recalling and rewriting my own string again and again.

It looks like what you're looking for is to have one list that comes directly from your text file. There's lots of ways to do that, but you most likely won't want to create a list iteratively with the index position. I would say to just append items to your list.
The accepted answer on this post has a good reference, which is basically the following:
import csv
with open('filename.csv', 'r') as fd:
reader = csv.reader(fd)
for row in reader:
# do something
Which, in your case would mean something like this:
import csv
actual_text_list = []
with open('filename.csv', 'r') as fd:
reader = csv.reader(fd)
for row in reader:
actual_text_list.append(row)
user_input_list = []
for actual_text in actual_text_list:
the_users_input = input(f'What is your response to {actual_text}? ')
user_input_list.append(the_users_input)
This creates two lists, one with the actual text, and the other with the other's input. Which I think is what you're trying to do.
Another way, if the list in your text file will not have duplicates, you could consider using a dict, which is just a dictionary, a key-value data store. You would make the key the actual_text from the file, and the value the user_input. Another technique, you could make a list of lists.
import csv
actual_text_list = []
with open('filename.csv', 'r') as fd:
reader = csv.reader(fd)
for row in reader:
actual_text_list.append(row)
dictionary = dict()
for actual_text in actual_text_list:
the_users_input = input(f'What is your response to {actual_text}? ')
dictionary[actual_text] = the_users_input
Then you could use that data like this:
for actual_text, user_input in dictionary.items():
print(f'In response to {actual_text}, you specified {user_input}.')

list_of_strings_from_txt = ["A","B","C"]
modified_list = [f"{w}: {input(f'{w}:')}" for w in list_of_strings_from_txt]
I guess? maybe?

Related

Convert excel or csv to list or dictionary, or word doc to list in python

I want my end-result to be a dictionary like the below.
mydict = {0:'term1', 1:'term2',...'159:'term160'}
I have a csv that has a single column of data, with a few words in each cell of the column's single row.
So far none of the suggestions I've found on here have helped. The closest I came was where one formula created multiple ordered dictionaries that from my single column created dictionaries like the below:
{['term1'], ['term2']}
{['term1'], ['term3']}
{['term1'], ['term4']}
So, instead of doing that, I thought I would just create a list from the column. When using the code below, rather that getting something like ['term1', 'term2', 'term3',...'term160'], I instead received [['term1'],['term2'],...['term160']], which when combined with my_list2 = list(range(0, 160)) via my_dict = dict.fromkeys(my_list_numbers, my_list_terms), printed out a dictionary of each number in the range matched with the entirety of the [['term1'],['term2'],...['term160']]
import csv
with open('filename.csv') as file:
reader = csv.reader(file)
data = list(reader)
print(data)
I just want either a dictionary or a list of strings that I can turn into a dictionary so that I don't have to type out multiple dictionaries of 100+ pairs each. I've been googling and experimenting for over an hour. I'm relatively new to code, but I feel like it shouldn't be this hard to extract a list of strings from an excel, csv, word, or text doc. Or simply format that from a list that I paste into the cell, even.
Any help would be greatly appreciated.
Assuming a data in file temp.csv as follows:
this_is_r1
this_is_r2
this_is_r3
this_is_r4
You can write your code as:
import os
os.chdir("/home/username/Downloads")
res= dict()
with open("temp.csv", "r") as f:
for k,x in enumerate(f):
res[k] = x.replace("\n","")
print(res)
The output is:
{0: 'this_is_r1', 1: 'this_is_r2', 2: 'this_is_r3', 3: 'this_is_r4', 4: 'this_is_r5', 5: 'this_is_r6'}
As suggested by Miguel Trejo, you can also use dictionary comprehension as:
with open("temp.csv", "r") as f:
res={k:x.replace("\n","") for k,x in enumerate(f)}
print(res)

Check for key in csv file if key is matched then add data into different rows of matched column using python

I have csv file like below
I need to search for a key then some values should be added in that key column. for example I need to search for folder and some values should be added in folder column. in the same way I need to search for name and some values should be added in name column.
so the final output looks like below
I have followed the below way but it doesn't work for me
import csv
list1 = [['ab', 'cd', 'ed']]
with open('1.csv', 'a') as f_csv:
data_to_write_list1 = zip(*list1)
writer = csv.writer(f_csv, delimiter=',', dialect='excel')
writer.writerows(data_to_write_list1)
If you want to only use built-in methods, you can get the first row of a file (in the case of a CSV file like yours, the headers) like this:
>>> with open('file_you_need.csv', 'r') as f:
>>> file = f.readline()
In your case the variable file would then be (supposing the delimiter is ","):
folder,name,service
You can now do file.split(",") (eventually replacing "," with whatever your delimiter is) and you'll get back a list of headers. You can then create a list of lists where each list is a row of your file and write back to the file or use a dictionary to link new entries to each header. Depending on your choice you would then in different ways write back to the file, i.e. supposing you go with list of lists:
with open('file_you_need.csv','w') as f:
for list in listoflists:
row = ""
for el, i in enumerate(list):
if i != len(list):
row += el+","
else:
row += el
f.write(row)
As others have mentioned you could also use Pandas and DataFrames to make it cleaner, but I don't think this is too hard to grasp

Python 3, how to append tuples into list

I just started to learn python. I need to store a csv file data into a list of tuples: tuples to represent the values on each row, list to store all the rows.
The function I have problem with is when I need to filter the list. Basically create a copy of the list with only the ones that met criteria. I have successfully appended all the tuples into a list, but when I need to append the tuples into a new list, it doesn't work.
def filterRecord():
global filtered
filtered = list()
try:
if int(elem[2])>= int(command[-1]): #the condition
#if I print(elem) here, all results are correct
filtered.append(tuple(elem)) #tuples do not add into the list
#len(filtered) is 0
except ValueError:
pass
def main():
infile = open('file.csv')
L = list()
for line in infile:
parseLine() #a function store each row into tuple
for line in stdin:
command = line.split() #process user input, multiple lines
for elem in L:
if command == 0:
filterRecord()
If I run it, the program doesn't response. If I force stop it, the traceback is always for line in stdin
Also, I am not allowed to use the csv module in this program.
I think you need to import sys and use for line in sys.stdin
You should use python's built-in library to parse csv files (unless this is something like a homework assignment): https://docs.python.org/2/library/csv.html.
You can then do something like:
import csv
with open ('file.csv', 'r') as f:
reader = csv.DictReader(f, delimiter=",")

Extracting variable names and data from csv file using Python

I have a csv file that has each line formatted with the line name followed by 11 pieces of data. Here is an example of a line.
CW1,0,-0.38,2.04,1.34,0.76,1.07,0.98,0.81,0.92,0.70,0.64
There are 12 lines in total, each with a unique name and data.
What I would like to do is extract the first cell from each line and use that to name the corresponding data, either as a variable equal to a list containing that line's data, or maybe as a dictionary, with the first cell being the key.
I am new to working with inputting files, so the farthest I have gotten is to read the file in using the stock solution in the documentation
import csv
path = r'data.csv'
with open(path,'rb') as csvFile:
reader = csv.reader(csvFile,delimiter=' ')
for row in reader:
print(row[0])
I am failing to figure out how to assign each row to a new variable, especially when I am not sure what the variable names will be (this is because the csv file will be created by a user other than myself).
The destination for this data is a tool that I have written. It accepts lists as input such as...
CW1 = [0,-0.38,2.04,1.34,0.76,1.07,0.98,0.81,0.92,0.70,0.64]
so this would be the ideal end solution. If it is easier, and considered better to have the output of the file read be in another format, I can certainly re-write my tool to work with that data type.
As Scironic said in their answer, it is best to use a dict for this sort of thing.
However, be aware that dict objects do not have any "order" - the order of the rows will be lost if you use one. If this is a problem, you can use an OrderedDict instead (which is just what it sounds like: a dict that "remembers" the order of its contents):
import csv
from collections import OrderedDict as od
data = od() # ordered dict object remembers the order in the csv file
with open(path,'rb') as csvFile:
reader = csv.reader(csvFile, delimiter = ' ')
for row in reader:
data[row[0]] = row[1:] # Slice the row up into 0 (first item) and 1: (remaining)
Now if you go looping through your data object, the contents will be in the same order as in the csv file:
for d in data.values():
myspecialtool(*d)
You need to use a dict for these kinds of things (dynamic variables):
import csv
path = r'data.csv'
data = {}
with open(path,'rb') as csvFile:
reader = csv.reader(csvFile,delimiter=' ')
for row in reader:
data[row[0]] = row[1:]
dicts are especially useful for dynamic variables and are the best method to store things like this. to access you just need to use:
data['CW1']
This solution also means that if you add any extra rows in with new names, you won't have to change anything.
If you are desperate to have the variable names in the global namespace and not within a dict, use exec (N.B. IF ANY OF THIS USES INPUT FROM OUTSIDE SOURCES, USING EXEC/EVAL CAN BE HIGHLY DANGEROUS (rm * level) SO MAKE SURE ALL INPUT IS CONTROLLED AND UNDERSTOOD BY YOURSELF).
with open(path,'rb') as csvFile:
reader = csv.reader(csvFile,delimiter=' ')
for row in reader:
exec("{} = {}".format(row[0], row[1:])
In python, you can use slicing: row[1:] will contain the row, except the first element, so you could do:
>>> d={}
>>> with open("f") as f:
... c = csv.reader(f, delimiter=',')
... for r in c:
... d[r[0]]=map(int,r[1:])
...
>>> d
{'var1': [1, 3, 1], 'var2': [3, 0, -1]}
Regarding variable variables, check How do I do variable variables in Python? or How to get a variable name as a string in Python?. I would stick to dictionary though.
An alternative to using the proper csv library could be as follows:
path = r'data.csv'
csvRows = open(path, "r").readlines()
dataRows = [[float(col) for col in row.rstrip("\n").split(",")[1:]] for row in csvRows]
for dataRow in dataRows: # Where dataRow is a list of numbers
print dataRow
You could then call your function where the print statement is.
This reads the whole file in and produces a list of lines with trailing newlines. It then removes each newline and splits each row into a list of strings. It skips the initial column and calls float() for each entry. Resulting in a list of lists. It depends how important the first column is?

Python: Compare List with a List in File

I am strugling with this problem that looks simple but I'm stuck! Well, I have to build a function where I receive a list of categories like:
input Example1: ['point_of_interest', 'natural_feature', 'park', 'establishment']
input Example2: ['point_of_interest', 'establishment']
input Example3: ['sublocality', 'political']
So that list could be with variable elements inside I guess from 1 till 4 not more
So with this same data I am gonna create a file with that input in a way that if the new input is not in the file, append it to the file.
The way is each list is an element itself, I mean I have to compare the full elements of the list and if I can find other list exactly equal I don´t have to add it.
In my code I just tried to add the first element in the file because really I don't know how to add the full list to compare with the next list.
def categories(category):
number = 0
repeat = False
if os.path.exists("routes/svm/categories"):
with open('routes/svm/categories', 'rb') as csvfile:
spamreader = csv.reader(csvfile)
for categoryFile in spamreader:
if (cmp(categoryFile,category) == 0):
number += 1
repeat = True
if not repeat:
categoriesFile = open('routes/svm/categories', 'a')
category = str(category[0])
categoriesFile.write(category)
categoriesFile.write('\n')
categoriesFile.close()
else:
categoriesFile = open('routes/svm/categories', 'w')
category = str(category[0])
categoriesFile.write(category)
categoriesFile.write('\n')
categoriesFile.close()
EDIT: Some explanation by #KlausWarzecha: Users might enter a list with (about 4) items. If this list ( = this combination of items) is not in the file already, you want to add the list (and not the items separately!) to the file? –
The problem is really simple. You may take the following approach if it works for you:
Read all the contents of the CSV into a list
Add all the non-matching items from the input into this list
re-write the CSV file
You may start with this sample code:
# input_list here represents the inputs
# You may get input from some other source too
input_list = [['point_of_interest', 'natural_feature', 'park', 'establishment'], ['point_of_interest', 'establishment'], ['sublocality', 'political']]
category_list = []
with open('routes/svm/categories', 'rb') as csvfile:
spamreader = csv.reader(csvfile)
for categoryFile in spamreader:
print categoryFile
category_list.append(categoryFile)
for item in input_list:
if (item in category_list):
print "Found"
else:
category_list.append(item)
print "Not Found"
# Write `category_list` to the CSV file
Please use this code as a starting point and not as a copy-paste solution.

Categories

Resources