使用for循环但忽略第一项?

Joh*_*nna 1 python for-loop character-encoding

我有一个小问题.我在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)
Run Code Online (Sandbox Code Playgroud)

trainFile包含丹麦语的单词和标签,但这不是问题.问题是:因为文件是丹麦语,我必须# -*- coding: cp1252 -*-在第一行包含正确显示Python中的字符.但是,我的for循环("for open in open ...")应忽略关于编码的第一行,并开始在trainFile的第二行开始运行,其中实际数据开始.我该怎么做呢?

谢谢!

Ned*_*der 6

这是你可以跳过第一行的方法:

with open(trainFile) as f:
    next(f)  # discard the first line
    for line in f:
        # deal with the rest.
Run Code Online (Sandbox Code Playgroud)

更好的选择可能是跳过以下开头的行#:

with open(trainFile) as f:
    for line in f:
        if line.startswith('#'):
            continue
        # deal with the rest.
Run Code Online (Sandbox Code Playgroud)