How to insert two file.txt into one file - python-2.7

I have this function that takes two input .txt file, delete the punctuation mark, and adds the sentence pos or neg.
I would like the content of these fle converted to lowercase
and then these two files merged into a single file name union.txt
But my code does not work
def extractor (feature_select):
posFeatures = []
negFeatures = []
with open('positive.txt', 'r') as posSentences:
for i in posSentences:
posWords = re.findall(r"[\w']+|[(,.;:*##/?!$&)]", i.rstrip())
posWords = [feature_select(posWords), 'pos']
posFeatures.append(posWords)
with open('negative.txt', 'r') as negSentences:
for i in negSentences:
negWords = re.findall(r"[\w']+|[(,.;:*##/?!$&)]", i.rstrip())
negWords = [feature_select(negWords), 'neg']
negFeatures.append(negWords)
return posFeature, negFeature
filenames = [posFeature, negFeature]
with open('union.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())

Actually you are trying to open the files with names from the contents of the two files. fname holds the contents read from the input files.
filenames = [posFeature, negFeature]
with open('union.txt', 'w') as outfile :
for i in filenames : #refers to posFeature or negFeature which is a list
for j in i: #this loop reads each sentence from the list i
outfile.write(j) #it writes the sentence into outfile
No need to read back the contents already read and appended in posFeature and negFeature. Above code will directly write the contents in the list filenames and now your two files are merged.

Related

rstrip, split and sort a list from input text file

I am new with python. I am trying to rstrip space, split and append the list into words and than sort by alphabetical order. I don’t what I am doing wrong.
fname = input("Enter file name: ")
fh = open(fname)
lst = list(fh)
for line in lst:
line = line.rstrip()
y = line.split()
i = lst.append()
k = y.sort()
print y
I have been able to fix my code and the expected result output.
This is what I was hoping to code:
name = input('Enter file: ')
handle = open(name, 'r')
wordlist = list()
for line in handle:
words = line.split()
for word in words:
if word in wordlist: continue
wordlist.append(word)
wordlist.sort()
print(wordlist)
If you are using python 2.7, I believe you need to use raw_input() in Python 3.X is correct to use input(). Also, you are not using correctly append(), Append is a method used for lists.
fname = raw_input("Enter filename: ") # Stores the filename given by the user input
fh = open(fname,"r") # Here we are adding 'r' as the file is opened as read mode
lines = fh.readlines() # This will create a list of the lines from the file
# Sort the lines alphabetically
lines.sort()
# Rstrip each line of the lines liss
y = [l.rstrip() for l in lines]
# Print out the result
print y

How to write rows into txt file python

I have code to write files to writer and then use writer to write into csv.
This is all using 'import csv' library.
But the problem is, I have numbers like 123456789.123456789 and when it writes into csv the number got truncate into 123456789.1234. so I want to write the results to txt instead, but don't know how to write rows to txt.
if results.get('rows', []):
for row in results.get('rows'):
for i in range(len(row)):
old, new = row[i], str()
for s in old:
new += s if s in string.printable else ''
row[i]=new
writer.writerow(row)
path = '/Users/sailormoon/Desktop/'
filename = 'sailormoon.csv'
with open(path + filename, 'wt') as f:
writer = csv.writer(f, lineterminator='\n')
Pseudo code I think:
path = '/Users/sailormoon/Desktop/'
filename = 'sailormoon.txt'
with open(path + filename, 'wt') as f:
f.write(row)
what library I can use to write rows into txt for python? Thanks!
Append all your numbers to a list as strings. Then use a for loop:
numbers = ['123456789.123456789', '123453459.128967678']
with open(path + '\\numbers.txt', 'w') as out:
for n in numbers:
out.write(n + '\n')

Python: count frequency of words in a txt file

I am required to count the frequency of the key words from a text file. I am not allowed to use dictionaries or sets, and I also cannot import any Python methods. I honestly cannot figure out how to do it!!
This is how its supposed to display:
car 4
dog 4
egg 3
here's what i have so far, and it absolutely does not work.
fname = input("enter file name:")
ifile = open(fname, 'r')
list1 = ['car', 'dog', 'cat'.....'ect']
list2 = []
for word in ifile:
if word in list1:
list2.index(word)[1] += 1
else:
list2.append([word,])
print(list2,)
I played with this a little... I noticed I had to enter file name in quotes for some reason.
fname = input('enter file name:')
ifile = open(fname, 'r')
list1 = []
list2 = []
for line in ifile.readlines():
for word in line.split(' '):
word = word.strip()
if word in list1:
list2[list1.index(word)] += 1
else:
list1.append(word)
list2.append(1)
for item in list1:
print item, list2[list1.index(item)]
Given you can't use any set/list structures why not use another string and write the unique words encountered, incrementing on existence. Pseudocode:
create empty string for storage
parse and extract words
iterate
check word against string (if exists: increment / ifnot exists: add and set count to 1)
output string

List to Text or Replace word in Text File

So I have a text file that contains:
Toy_One Ordered
Toy_Two Ordered
Toy_Three Ordered
I want to remove the " Ordered" from the text file. I figured making a list and rewriting to the file would be simple, or even a replace but clearly not. So far, I have been only able to rewrite Toy_Three.
Infile = (src.txt, "r")
g = list(Infile)
stripg = [mark.strip() for mark in g]
for line in stripg:
entry = line.split(" Ordered")
NewList = list(entry[0])
InOutFile = (src, "w")
for final in NewList:
InOutFile.write(final)
My outcome is just Toy_Three
I've also tried "pickle" but with no success.
Any help would be appreciated, thanks.
Nevermind, got it:
Infile = (src.txt, "r")
magic = Infile.readlines()
delete = [" Ordered"]
Outfile = (src.txt, "w")
for line in magic:
for word in delte:
line = line.replace(word,"")
Outfile.write(line)

Python CSV export writing characters to new lines

I have been using multiple code snippets to create a solution that will allow me to write a list of players in a football team to a csv file.
import csv
data = []
string = input("Team Name: ")
fName = string.replace(' ', '') + ".csv"
print("When you have entered all the players, press enter.")
# while loop that will continue allowing entering of players
done = False
while not done:
a = input("Name of player: ")
if a == "":
done = True
else:
string += a + ','
string += input("Age: ") + ','
string += input("Position: ")
print (string)
file = open(fName, 'w')
output = csv.writer(file)
for row in string:
tempRow = row
output.writerow(tempRow)
file.close()
print("Team written to file.")
I would like the exported csv file to look like this:
player1,25,striker
player2,27,midfielder
and so on. However, when I check the exported csv file it looks more like this:
p
l
a
y
e
r
,
2
5
and so on.
Does anyone have an idea of where i'm going wrong?
Many thanks
Karl
Your string is a single string. It is not a list of strings. You are expecting it to be a list of strings when you are doing this:
for row in string:
When you iterate over a string, you are iterating over its characters. Which is why you are seeing a character per line.
Declare a list of strings. And append every string to it like this:
done = False
strings_list = []
while not done:
string = ""
a = input("Name of player: ")
if a == "":
done = True
else:
string += a + ','
string += input("Age: ") + ','
string += input("Position: ") + '\n'
strings_list.append(string)
Now iterate over this strings_list and print to the output file. Since you are putting the delimiter (comma) yourself in the string, you do not need a csv writer.
a_file = open(fName, 'w')
for row in strings_list:
print(row)
a_file.write(row)
a_file.close()
Note:
string is a name of a standard module in Python. It is wise not to use this as a name of any variable in your program. Same goes for your variable file