-3

I've just started learning python and am having a really hard time with some stuff. I have a textfile that has one source, like a reference in a scientific paper. I need to write a script that checks if the dates in this file are between 1900 and 2012. If so, it needs to list the dates vertically in a list.

If the source has the two dates 1934 and 1968 then it would be printed:

1934
1968

So far I have

f=open('filename.txt')
words=f.readlines()
year=range(1900,2013)

I have tried a variety of subsequent lines but never get anywhere. Example:

for year in words:
    print year

I'm not sure at all on how to proceed. Can anyone help, please?

4

1 回答 1

2

I think there are three things you need to do to make your code work. The first is to search your text file for digit characters using a simple regular expression and the re module. Then you need to convert each string you find to an integer. Finally, you can compare it with your boundary numbers:

import re

with open("filename.txt") as f:
    text = f.read()                     # read the whole file

for match in re.finditer(r"\d+", text): # find all strings of consecutive digits
    num = int(match.group())            # convert to integer
    if 1900 <= num <= 2013:             # test boundaries
        print num
于 2013-10-09T00:39:19.390 回答