Python nested list from file [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Let's say I have the following .txt file:
"StringA1","StringA2","StringA3"
"StringB1","StringB2","StringB3"
"StringC1","StringC2","StringC3"
And I want a nested list in the format:
nestedList = [["StringA1","StringA2","StringA3"],["StringB1","StringB2","StringB2"],["StringC1","StringC2","StringC3"]]
so I can access StringB2 for example like this:
nestedList[1][1]
What would be the best approach? I do not have a tremendous amount of data, maybe 100 lines at max, so I don't need a database or something

You can this sample code:
with open('file.txt') as f:
nestedList = [line.split(',') for line in f.readlines()]
print(nestedList[1][1])

file = open('a.txt').read()
file
l=[]
res = file.split('\n')
for i in range(len(res)):
l.append(res[i].split(','))
print(l[1][1])
Assuming your file name as a.txt is having data in same format as you specified in question, i.e newline seperated so that we can add nested list, and data inside is ,(comma) seperated. Above code will give you the right output.

Related

How to split the input in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
I have the input like this
8.8.8.8,678,fog,hat
8.8.4.4,5674,rat,fruit
www.google.com,1234,can,zone
I want to split this input in Python so that only the IP address needs to be fetched which I will use for PING purpose. I really appreciate your help in this regard.
Guessing that your input is in a .csv file.
You could use Pandas or built in csv library to parse it. Using the latter in the example below.
import csv
with open("my_input.csv") as file:
csv_reader = csv.reader(file, delimiter=",")
ip_adresses = [ip for ip, *_ in csv_reader]
print(ip_adresses)
>> ['8.8.8.8', '8.8.4.4', 'www.google.com']
I collect the first item of the each row by using list unpacking.
Let's say one line of your data is in a variable called line. Then you can get the ping address this way:
ping = line.split(',')[0]

I have a text file which contains sets , how do i read them as sets when i load on python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
My text file looks like this
{} /n {}/n
When I use readline, I get it as a list , like ['{}' , '{}]
how do I remove the string and read them as sets?
This code work for you.
with open('yourfile.txt','r') as file:
data = file.read().splitlines()
data = [set(a[1:-1].split(',')) for a in data]
print(data)
You can use eval also here, But using eval might be dangerous.
with open('yourfile.txt','r') as file:
data = file.read().splitlines()
data = [eval(a) for a in data]
print(data)

How to compare each line of a text file with a statement? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Let's say I have a text file of links and garbage which look like this:
www.facebook.com
www.google.com
123
fewfwfqwfq
Let's do a for loop and compare each line and if there is not a ".com" in the specific line, the line gets deleted. In that case '123' and 'fewfwfqwfq' gets deleted.
How can I achieve that?
good_lines = [l for l in links if '.com' in l]
with open('fname.txt') as fout:
[fout.write(g) for g in goodlines]

How to read values from a file and set dynamically into an array in Python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Im new to python and need to know how to achieve the below requirement
I have a file with values populated as lines separated
for eg.
ABC
DEF
GHI
I want to read these values from a file and need to set them in the below format in python, basically into a dictionary.
{"Keys":[{"common_key":"ABC"},{"common_key":"DEF"},{"common_key":"GHI"}]}
Dictionary should contain only one Key and its value is an array with set of jsons with a common key assigned with different values each which are read from the file.
This way works for me:
with open('filename.txt') as fin :
lines = [i.strip() for i in fin.readlines() if len(i) > 1]
common_dict = { 'Keys' : [ {'common_key' : i} for i in lines] }
The best way to do this would probably be a simple list comprehension. If you need to do any separation logic in the lines str.split() is your friend.
with open("filename.txt") as txtfile:
yourDesiredDict = {"Keys": [{"common_key": x} for x in txtfile.readlines()]}

Parsing txt using python sets data structure [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
how can i parse this so that I can obtain how many unique urls there are regardless of the number behind it ? using python
You can open the file and get the lines as a string using:
with open("/path/to/file.txt") as file:
lines = list(file)
This will give you a list of all lines in the text file.
Now since you do not want duplicates, I think using set would be a good way. (Set does not contain duplicates)
answer=set()
for x in lines:
answer.add(x[x.find(" ")+1:x.rfind(":")])
This will iterate through all the lines and add the part after the space till and not including the : to the set, which will handle the case for duplicates. Now answer should contain all the unique urls
Tested for Python3.6
You can use regex to parse and extract uids from your file line per line.
import re
uids = set()
with open('...') as f:
for line in f:
m = re.match('$[a-z0-9]+', line)
if m:
uids.add(m.group(0))
print(len(uids))
import re
A, List = ("String_1 URL_1:10\nString_2 URL_2:20\nString_3 URL_1:30".replace(" ", ",")).split("\n"), []
for x in range(len(A)):
Result = re.search(",(.*):", A[x])
if Result.group(1) not in List:
List.append(Result.group(1))
print(len(List))
This should solve your problem.

Categories