Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在文件中指定要打印的行_Python 3.x - Fatal编程技术网

Python 3.x 在文件中指定要打印的行

Python 3.x 在文件中指定要打印的行,python-3.x,Python 3.x,因此,在我打开一个文件后,下面的代码应该通读这些行,并且只打印包含我输入的年份和我输入的收入代码的行,但是对于收入,我必须输入一个数字1-4,表示word文件中的一行,我如何写它,以便数字识别该单词 input_year = input("Enter a year:") print() print("Choose one of the following:") print("1 for low income.") print("2 for lower middle income.") prin

因此,在我打开一个文件后,下面的代码应该通读这些行,并且只打印包含我输入的年份和我输入的收入代码的行,但是对于收入,我必须输入一个数字1-4,表示word文件中的一行,我如何写它,以便数字识别该单词

input_year = input("Enter a year:")
print()

print("Choose one of the following:")
print("1 for low income.")
print("2 for lower middle income.")
print("3 for upper middle income.")
print("4 for high income.")
print()     

income_code_input = input("Enter income level:")


for line in input_file:
   line = line.strip()
   country = line[0:50]
   income = line[51:56]
   vaccination = line[59:60]
   region = line[62:83]
   year = line[-4:]

   if year.startswith(input_year) and income.startswith(income_code_input):
      print(line.rstrip())

没有指定数据格式,因此我只能猜测收入字段的开头。这是我的猜测:

code = {'1':'low ', '2':'lower', '3':'upper', '4':'high'}
if year.startswith(input_year) and income.startswith(code[income_code_input]):
    print(line.rstrip())
上面使用字典
code
,将用户输入的数字转换为收入字段开头的字符串。注意
input
返回一个字符串,以便
code
字典中的键都是字符串,例如
'1'
,而不是数字,例如
1
。还要注意,我们需要区分“低”和“低”。因此,我在
code[1]
的值的“low”后面保留了一个尾随空格