0

I am trying to process a txt file I created of songs and genres, but don't know how to tell python what to look for. The txt file is formatted like so:

  1. 7/28/2012

1.1. Lovin’ You Is Fun—Country

[...]

1.100. Call Me Maybe—Teen pop, dance-pop

[]2. 7/27/2013

2.1. Crown—Hip hop

(brackets not in actual file)

I've tried writing code to find certain words in lines, but the code finds every line of the file as containing whatever string I pass it (even when that's obviously not the case). Here's the code:

try:
    infilehandle = open(afile, "r")
    alllines = infilehandle.read().splitlines(False)
    infilehandle.close()
except:
    alllines=None
    print "Unable to read file {0}".format(afile)
for aline in alllines:
    if aline.find("Country"):
        country_count += 1
    if aline=="1.   7/28/2012" or "2.   7/27/2013" or "3.   4/27/2013" or "3.   4/27/2013":
        continue
    else:
        continue

If the code worked the way I wanted it to, it would categorize each line by the first number on the line, then search for certain strings and add to a count for those strings. Is this possible to do?

2 Answers2

1

You should write:

  if aline.find("Country") != -1:

or even better would be

  if "Country" in aline:

Also, your second if should read:

  if aline=="foo" or aline=="bar" or aline=="zom":
0

Find doesn't return a boolean. It returns an int. In particular, it returns -1 if it doesn't find the string.

And as jonrsharpe mentions, you are using or incorrectly, also.

try:
    infilehandle = open(afile, "r")
    alllines = infilehandle.read().splitlines(False)
    infilehandle.close()
except:
    alllines=None
    print "Unable to read file {0}".format(afile)
    exit(1)
for aline in alllines:
    if aline.find("Country") != -1:
        country_count += 1
    if aline=="1.   7/28/2012" or
       aline=="2.   7/27/2013" or
       aline=="3.   4/27/2013" or
       aline=="3.   4/27/2013":
        pass  # I have no idea what you're trying to do here
ooga
  • 15,423
  • 2
  • 20
  • 21