python-3.x - 如何使用变量剥离()和拆分()?
问题描述
W_A11, 2008-02, Moving average, 59.66666667, 50.92582302, 68.40751031, Injuries, Number, Assault, Validated, Whole pop, All ages, Fatal,
W_A11, 2010-03, Moving average, 60, 51.23477459, 68.76522541, Injuries, Number, Assault, Validated, Whole pop, All ages, Fatal,
W_A11, 2017-04, Moving average, 59, 50.30812505, 67.69187495, Injuries, Number, Assault, Validated, Whole pop, All ages, Fatal
qdate = int(input("please enter 2000, 2010, or 2017"))
infile = open('injury_statistics.txt', "r")
outfilename = input("please enter the name of the file to which you want to
append ex) injury_statistics_datafile.txt ")
outfile = open(outfilename, "a")
stripped_character = input("please enter any character you want stripped
from the data ")
delimiter = input("please enter the delimiter for the file ")
# print(type(stripped_character))
# print(type(delimiter))
# the above two lines prove that stripped_character and delimiter are
# strings
next(infile)
for line in infile:
linefromfile = line.strip(stripped_character).split(delimiter)
tuple1 = tuple(linefromfile)
if int(tuple1[1][:4]) == qdate:
outfile.write('\n')
outfile.write(str(linefromfile))
infile.close()
outfile.close()
剥离和拆分都采用字符串 ex) split('\t'),但由于某种原因,我的变量“stripped_character”和“delimiter”存储的字符串不能正常工作(我认为它们返回空字段)。如果我手动输入一些值,则此代码有效,例如)linefromfile = line.strip('\n').split('\t')。
回溯错误如下所示: Traceback (最近一次调用最后一次): File "C:/Users/Hezekiah/PycharmProjects/Great Courses Python/testing.py", line 14, in if int(tuple1[1][:4] ) == qdate: IndexError: 元组索引超出范围
解决方案
推荐阅读
- c++ - Retrieve used header and source file names by parsing Makefile
- c++ - 在 Clang 中生成默认构造函数
- ruby-on-rails - Rails 单选按钮参数是字符串而不是哈希
- git - 恢复合并的多个分支以开发
- css - 如何在浏览器 ionic 3 中滑动水平滚动
- sql-server - 如何在 PHP 7 上使用 ODBC 驱动程序 17 连接到命名实例?
- shopify - Shopify ResourcePicker 未显示
- javascript - 如何在 React Native ListView 中过滤和呈现重复的嵌套 JSON 数据?
- reactjs - 推送到 MenuItem 的搜索结果不正确 - React
- python-3.x - python脚本通过'import psutil'在终端中失败