[英]Error: File “xml_parser.py”, line 5, in <module> out_file = sys.argv[2] IndexError: list index out of range
[英]IndexError: list index out of range, line 42, in <module> main()line 14, in main sent_file = open(sys.argv[1])
import sys
import json
# subroutine for calculating setiment scores for each tweets
def compute_score(text,scores):
total = 0.0
words = text.split()
for word in words:
if word in scores.keys():
total = total + scores[word]
return total
def main():
sent_file = open(sys.argv[1]) # first argument of the function call is the sentiment file
tweet_file = open(sys.argv[2]) # second argument of the function call is the tweets file
# creating a dictionary for sentiment-word mapping
scores = {} # initialize an empty dictionary to store sentiment scores for words
for line in sent_file:
term, score = line.split("\t") # The file is tab-delimited. "\t" means "tab character"
scores[term] = int(score) # Convert the score to an integer.
# creating a dictionary for tweet-sentiment_score mapping
tweets_scores = {} # initialize an empty dictionary
index = 0
for line in tweet_file:
index = index + 1
tweet = json.loads(line)
text = tweet.get("text")
# calculating setiment score
if text:
text = text.encode("utf-8")
tweets_scores[index] = compute_score(text,scores)
else: tweets_scores[index] = 0.0
# print out results
for i in tweets_scores:
print(str(tweets_scores[i]))
if __name__ == '__main__':
main()
您必须将文件名指定为命令行参数。 sys.argv是传递给Python脚本的命令行参数列表。
python test.py sen.txt twt.txt
您应该在command line
运行该程序并提供这2个参数。 像这样,在当前dir运行终端中:
python filename.py param1 param2
filename.py
是您的文件名称, param1
是第一个参数, param2
是第二个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.