2012-09-22 55 views
9

我的python程序在打开文本文件时遇到问题。当我使用基本的打开文件进行读取时,出现ascii错误。有人通过让我添加一个在Idle中运行良好的编码参数来帮助我,但是当我通过终端运行程序时,出现此错误消息:“TypeError:'encoding'是此函数的无效关键字参数。”我怎样才能读这个文本文件来使用它的数据?TypeError:'encoding'是此函数的无效关键字参数

try: 
    import tkinter as tk 
    from tkinter import * 
except: 
    import Tkinter as tk 
    from Tkinter import * 

import time 
import sys 
import os 
import random 

flashcards = {} 


def Flashcards(key, trans, PoS): 
    if not key in flashcards: 
     flashcards[key] = [[trans], [PoS]] 
    else: 
     x = [] 
     for item in flashcards[key][0]: 
      x.append(item) 
     x.append(trans) 
     flashcards[key][0] = x 
     x = [] 
     for item in flashcards[key][1]: 
      x.append(item) 
     x.append(PoS) 
     flashcards[key][1] = x 


def ImportGaeilge(): 
    flashcards = {} 
    with open('gaeilge_flashcard_mode.txt','r', encoding='utf8') as file: 
     for line in file: 
      line1 = line.rstrip().split("=") 
      key = line1[0] 
      trans = line1[1] 
      PoS = line1[2] 
      Flashcards(key, trans, PoS) 

def Gaeilge(): 
    numberCorrect = 0 
    totalCards = 0 
    ImportGaeilge() 
    wrongCards = {} 
    x = input('Hit "ENTER" to begin. (Type "quit" to quit)') 
    while x != quit: 
     os.system('cls') 
     time.sleep(1.3) 
     card = flashcards.popitem() 
     if card == "": 
## WRONG CARDS 
      print ("Deck one complete.") 
      Gaeilge() 
     print("\n\n") 
     print(str(card[0])+":") 
     x = input("\t:") 
     if x == 'quit': 
      break 
     else: 
      right = False 
      for item in card[1]: 
       if x == card[1]: 
        right = True 
        print("\nCorrect!") 
        numberCorrect += 1 
      if right == False: 
       print(card[0]) 

     totalCards += 1 
     print("Correct answers:", str(numberCorrect) +"/"+str(totalCards)) 


Gaeilge() 

gaeilge_flashcard_mode.txt:

I=mé=(pron) (emphatic) 
I=mise=(n/a) 
you=tú=(pron) (subject) 
you=tusa=(emphatic) 
y'all=sibh=(plural) 
y'all=sibhse=(emphatic) 
he=sé=(pron) 
he=é=(n/a) 
he=seisean=(emphatic) 
he=eisean=(n/a) 
she=sí=(pron) 
she=í=(n/a) 
she=sise=(emphatic) 
she=ise=(emphatic) 
him=é=(pron) 
him=eisean=(emphatic) 
her=í=(pron) 
her=ise=(emphatic) 
her=a=(adj) 

回答

12

您尝试在运行此终端可能使用Python 2.x的标准。

尝试使用命令 “Python3” 特别是在终端:

$ Python3 yourfile.py

3

1(测试和证实2.7将给出错误,并且Python3处理它就好了。)给Unfun猫一个关于Linux的正确答案等。

但是,对于Windows用户,调用'Python3'通常不起作用。但是,如果你已经安装了Python 3.3(如果您已经下载并安装了Python启动的Windows),您可以键入:

C:\scr>py -3 yourfile.py 

其实,这种发射器也支持家当语法,所以添加以下第一线你的脚本文件将相当跨平台工作(在/ usr/bin中的Windows上被忽略):

#! /usr/bin/python3 

这样做之后,假设WINDOWS \ py.exe是.py文件的默认处理程序,你可以只需键入:

C:\scr>yourfile.py 

如果 “py” 为是你的PATHEXT环境变量中,你可以只输入:

C:\scr>yourfile 

更多信息:

http://docs.python.org/3/whatsnew/3.3.html

http://www.python.org/dev/peps/pep-0397/

相关问题