Python 将数据加载到字典中
我参加了Coursera的数据科学课程,完成其中一项作业后,我开始编写此代码Python 将数据加载到字典中,python,Python,我参加了Coursera的数据科学课程,完成其中一项作业后,我开始编写此代码 import sys import json import re def lines(fp): print str(len(fp.readlines())) def main(): tweet_file = open(sys.argv[1]) word_frequency_count = {} for line in tweet_file:
import sys
import json
import re
def lines(fp):
print str(len(fp.readlines()))
def main():
tweet_file = open(sys.argv[1])
word_frequency_count = {}
for line in tweet_file:
raw_data = json.loads(line)
#print raw_data
text = raw_data.get('text', "").lower().encode('utf-8')
new_text=re.findall(r"[\w']+", text)
print new_text
#print text
for word in new_text:
word_frequency_count[word] = 'Test'
print word_frequency_count.items()
if __name__ == '__main__':
main()
new_text的print语句输出这样的行,并且有数千个这样的结果,这只是一个示例
['rt', 'fuadagus2', 'presiden', 'sby', 'belilah', 'nuklir', 'kpd', 'korut', 'luncurkan', 'ke', 'israel', 'tunjukan', 'kalau', 'kamu', 'islam', 'prayforgaza']
['not', 'letting', 'nothing', 'else', 'get', 'in', 'my', 'way']
困扰我的是字典键值对的最后一次打印,它只输出5个键值对。我是一名Java开发人员这是我第一次涉足python,我是否错过了任何明显的东西?第二个for循环
for word in new_text
在主循环(在文件中的行上循环)之外。这意味着它只会在主循环结束后执行一次。此时,新文本将只包含最后一行中的单词
尝试将第二个循环移动到主循环中。缩进错误:
for line in tweet_file:
...
for word in new_text:
word_frequency_count[word] = 'Test'
第二个循环发生在第一个循环之外,因此只处理tweet\u文件
中最后一行中的new\u text
列表。它应该是:
for line in tweet_file:
...
for word in new_text:
word_frequency_count[word] = 'Test'
但是,请注意Python附带了“电池”;在这种情况下,将使您的生活更加轻松。非常感谢。计数器确实非常有用。我在这上面浪费了8个小时。