我有一个小问题。我在 Python 中有这段代码(取自更大的脚本):
for line in open(trainFile):
for token,tag in [x.rsplit('/',1) for x in line.split()]:
tokenTagCount[(token,tag)] += 1
tags[tag] += 1
listOfTags.append(tag)
trainFile 包含丹麦语的单词和标签,但这不是问题所在。问题是这样的:因为文件是丹麦语的,所以我必须在第一行包含 # -*- coding: cp1252 -*- 才能正确显示 Python 中的字符。但是,我的 for 循环(“for line in open...”)应该忽略关于编码的第一行,并从 trainFile 的第二行开始运行,那里是实际数据的开始。我该怎么做?
谢谢!
请您参考如下方法:
这是您可以跳过第一行的方法:
with open(trainFile) as f:
next(f) # discard the first line
for line in f:
# deal with the rest.
更好的选择可能是跳过以 # 开头的行:
with open(trainFile) as f:
for line in f:
if line.startswith('#'):
continue
# deal with the rest.
