Ad

Append Next Word Into A List From A Text File In Python And Print It Columnwise

- 1 answer

number=[]
name=[]
null=[]
fh = open("foo.txt","r")
for line in fh:
 words=line.split()
 for word in words:
    if(word=="number"):
        number.append(word+1)
        print(word)
        word=word+2
    if(word=="name"):
        name.append(word+1)
        word=word+2
    else:
        null.append(word+1)
        word=word+2
print("number " " instances " " name " " instances " " null " " instances ")
print(number, len(number), name, len(name), null, len(null) )
fh.close()

This is my minimal python code. My objective here is to print columnwise the features (e.g. name) and the number of instances of it. My test file (foo.txt) is of the following order

name Mathew
null has
number 4
null dogs
null and
null a 
null cat

I know that my code is not right. Especially during the append statement and the increment statement. My question is: a. What would be the correct statement? b. What would i do to get a coulmnwise output, especially if there are a very large number of words, in other words, can i wrap in a column?

Expected output

number instances      name     instances     null         instances
  4        1         Mathew        1       has, dogs,         5
                                           and, a, cat

Absolute beginner here.

Ad

Answer

This works and I have used mostly your code so that it is easy for you to understand how to improve upon:

name=[]
null=[]
number=[]
fh = open("foo.txt","r")
for line in fh:
    word= line.split()[0]
    if word == "name":
        name.append(line.rstrip('\n').split()[1])
    elif word =="number":
        number.append(line.rstrip('\n').split("number")[1])
    else:
        null.append(line.rstrip('\n').split("null")[1])

print("number " " instances " " name " " instances " " null " " instances ")
print(" ".join(str(x) for x in number), len(number), " ".join(str(x) for x in name), len(name), " ".join(str(x) for x in null), len(null) )
Ad
source: stackoverflow.com
Ad