Merge two names /or just extract names from CSV file - python-3.x

I want to read csv file containing different names and merge two names into one.
for example:
google.com , facebook.com
should generate something like
googleface.com or googlebook.com
import csv
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
ps = PorterStemmer()
with open('C:/Users/upadh/Desktop/domains.txt', 'r') as csvFile:
csvReader = csv.DictReader(csvFile, delimiter=',')
string ={}
count =0
for row in csvReader:
# for row in csvReader:
#if row is 0 :
for header, value in row.items():
try:
string[header].append(value)
except KeyError:
string[header] = [value]
for w in sorted(str(string)):
print(w, " : ", ps.stem(w))

Extract names can be done like this:
import csv
with open('inputCSV.txt', 'r') as csvFile:
csvReader = csv.reader(csvFile, delimiter=',')
for line in csvReader:
#prints all 'names' in the csv file, here you can add code to do whatever.
[print(name) for name in line]

Related

CSV file: open in Python and print only links

I have CSV file with some links stored in one of the columns. I want to read only links and print them out. I tried to use following code but output is none.
import csv
filename ='abc.csv'
with open(filename,'rb') as f:
reader = csv.reader(f)
for row in reader:
for item in row:
if item.startswith('http'):
print(item)
import csv
with open ('abc.csv','r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
if line[0].startswith('http'):
print(line)
If you want to make sure that the line starts with for example "http" you should write:
line[0].startswith("http")because the first element of the line list will be a string.

Strange error when reading a CSV file through method

So, I've got a CSV file (league.csv') in my directory that I want to access through Python.
When I do this:
with open('league.csv', 'r') as csvFile:
csvReader = csv.reader(csvFile)
next(csvReader)
for line in csvReader:
print(line[0])
It works great. But when I try to make it into a function it doesn't work:
def createLeague(csv):
with open(csv, 'r') as csvFile:
csvReader = csv.reader(csvFile)
next(csvReader)
for line in csvReader:
print(line[0])
return
If I call this using:
createLeague('league.csv')
I get the error
csvReader = csv.reader(csvFile)
AttributeError: 'str' object has no attribute 'reader'
This makes no sense because type(csvFile) is not str, and I'm doing exactly the same as above?
Could someone help me, I'm getting really frustrated!
Thanks!
See inline comment what goes wrong.
import csv # "csv" variable at "with open..." overwrites
# cvs module.
from csv import reader # required to use the function "reader" from csv.
def createLeague(csv): # "csv" variable overwrites cvs module.
with open(csv, 'r') as csvFile:
csvReader = reader(csvFile) # skip the csv. here and it works for you.
next(csvReader)
for line in csvReader:
print(line[0])
return
Alternatively:
Below example with changed csv filename does not overwrite the csv module that you just have loaded. The mix-up triggers the error to occur.
import csv
#from csv import reader
def createLeague(csv_file):
with open(csv_file, 'r') as csvFile: # changed variable "csv" filename.
csvReader = csv.reader(csvFile)
next(csvReader)
for line in csvReader:
print(line[0])
return
Don’t use the name of the library as the name of the variable in the function definition.

Print output to separate text files

The script below opens devices.csv and reads the rows, then prints 2 of the fields. I want to create a separate .txt file for each row using 'Host Name' field, then print 'Configuration Text' to each file.
import csv
import sys
import os
path = 'C:/configs'
fh = "C:/configs/devices.csv"
with open(fh, mode='r') as infile:
reader = csv.DictReader(infile)
for row in reader:
print(row['Host Name'], row['Configuration Text'])
Please assist.
import csv
import sys
import os
path = 'C:/configs'
fh = "C:/configs/devices.csv"
with open(fh, mode='r') as infile:
reader = csv.DictReader(infile)
for row in reader:
with open(os.path.join(path, row['Host Name']), "w") as outfile: #Create File with host name
outfile.write(row['Configuration Text']) #Write Content

python3 import into csv displaying in every cell

I'm new to python and I'm trying to import some URL's i scraped into a csv file but it is parsing every character in the web addresses into a difference cell. Here's my code:
import csv
with open('test.csv', 'w') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['Web Address'])
csv_write.writerows(filter_records)
If i put brackets around the filter_records variable, it just returns the entire list of URLs in a single cell
Any guidance would be great.
Thanks
Garrett
You can do something like this:
import csv
filter_records = ['www.google.com', 'www.stackoverflow.com', 'www.facebook.com']
with open('test.csv', 'w') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['Web Address'])
[csv_writer.writerow([record]) for record in filter_records]
or
import csv
filter_records = ['www.google.com', 'www.stackoverflow.com', 'www.facebook.com']
with open('test.csv', 'w') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['Web Address'])
csv_writer.writerows([record] for record in filter_records)
This happens because python a string is a list of chars. writerow() method receives a list as param, and writerows() receives a list of lists. So, you will get an comma-split string in every row.

Writing to csv file more than one user input?

I have a user input. The first is for user to put in their name. The following will be destinations.
The below code writes to line 1 in csv. Hover if the code runs again and user inputs a different name I want it to write to the next line. Line 2.
class writeToCSVfile:
def __init__(self):
self.name = []
def writeIt(self):
import csv
with open('test.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
data = [['Name', 'Home Airport','Destination' 'Stopovers','Cheapest Route'],
[b.name, xy, b.input2, b.input3 ],
a.writerows(data)
writ = writeToCSVfile()
writ.writeIt()
What the CSV file looks like now
Just use append mode when openinig the file and should work:
with open('test.csv', 'a', newline='') as fp:
You must deal with the headers
['Name', 'Home Airport','Destination' 'Stopovers','Cheapest Route']
to not append them everytime to the file.

Resources