954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Print line number

Hello, I am new to daniWeb. I am creating a script but have run into a problem when it comes to printing the line number.

print
   for word in words:
      word = clearup(word)
      if word in dictionary:
         pass
      else:
         print word


On the last line I want to do something like... print word':'linenumber

Would I use something from " from linecache import getline "

I have tried:

linenum = getline(filepath, ##line_number##)
         print word.strip('.')
         print ' :(',
         print linenum
         print ')'


It doesn't work and prints Either data about a line of python code (not line number from the text file) or just prints a bunch of Trues... could someone please explain what I need to do?

Bouzy210
Newbie Poster
8 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

Okay, what it your whole program try and do? I'm not quite sure with the information given.

Paul Thompson
Veteran Poster
1,119 posts since May 2008
Reputation Points: 264
Solved Threads: 183
 

If you don't want to read all of my nonsense just skip to the example.

Basically, I have a tuple of words. I am comparing it to a doc.txt to see if the word from my tuple match any of the words in my document. If item in my tuple that matches an item in the document I pass else: i print the item. I want it to print the line number of the txt document along with the word if it doesn't match.

e.g.

My doc.txt has this in it:
good
bad
uligy

my_tuple (

"good"
"bad"
"ugly"

)

if word in dictionary:
         pass
      else:
         print word


that outputs ... uligy

What I want it to output is: uligy : line 3

Bouzy210
Newbie Poster
8 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

Enumerate is one way to do it.

for ctr, word in enumerate(words):
      word = clearup(word)
      if word not in dictionary:
         print "%s : line %d" % (word, ctr)
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

Thanks! I looked up enumerate and read about it. It was exactly what I needed.

Bouzy210
Newbie Poster
8 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

Mark then the thread solved

evstevemd
Senior Poster
3,713 posts since Jun 2007
Reputation Points: 462
Solved Threads: 392
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You