Write a program which reads a text file called input.txt which contains an arbitrary number of lines of the form ", " then records this information using a dictionary, and finally outputs to the screen a list of countries represented in the file and the number of cities contained.Python-文件解析
例如,如果input.txt中含有下列:
New York, US
Angers, France
Los Angeles, US
Pau, France
Dunkerque, France
Mecca, Saudi Arabia
方案將輸出下面(在一些順序):
Saudi Arabia : 1
US : 2
France : 3
我的代碼:
from os import dirname
def parseFile(filename, envin, envout = {}):
exec "from sys import path" in envin
exec "path.append(\"" + dirname(filename) + "\")" in envin
envin.pop("path")
lines = open(filename, 'r').read()
exec lines in envin
returndict = {}
for key in envout:
returndict[key] = envin[key]
return returndict
我得到一個語法錯誤:無效語法... wh我使用我的文件名 我用文件名input.txt
您忘了發佈迄今爲止編寫的代碼,問題,以及您如何嘗試/無法解決問題。 *然後*,有人可能會幫助你。 – mdm 2011-04-09 16:11:13
那麼,你到目前爲止嘗試過什麼? – 2011-04-09 16:11:36
你是怎麼調用'parseFile()'和你看到的語法錯誤是什麼? – Johnsyweb 2011-04-09 16:24:47