Append Next Word Into A List From A Text File In Python And Print It Columnwise
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?
number instances name instances null instances 4 1 Mathew 1 has, dogs, 5 and, a, cat
Absolute beginner here.
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() if word == "name": name.append(line.rstrip('\n').split()) elif word =="number": number.append(line.rstrip('\n').split("number")) else: null.append(line.rstrip('\n').split("null")) 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) )
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module