Вы можете использовать json_decode () для преобразования строки json в объект / массив PHP.
Например.
Вход:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
Выход:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Несколько точек для запоминания:
json_decode
требует, чтобы строка была действительной json
, иначе она вернется NULL
. json_last_error()
можно использовать для определения точного характера ошибки. utf8
контент, или json_decode
может выйти из строя и просто вернуть значение NULL
. Используйте метод update
для счетчика. Пример:
from collections import Counter
data = '''\
ashwin programmer india
amith programmer india'''
c = Counter()
for line in data.splitlines():
c.update(line.split())
print(c)
Выход:
Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})
FILE_NAME = 'file.txt'
wordCounter = {}
with open(FILE_NAME,'r') as fh:
for line in fh:
# Replacing punctuation characters. Making the string to lower.
# The split will spit the line into a list.
word_list = line.replace(',','').replace('\'','').replace('.','').lower().split()
for word in word_list:
# Adding the word into the wordCounter dictionary.
if word not in wordCounter:
wordCounter[word] = 1
else:
# if the word is already in the dictionary update its count.
wordCounter[word] = wordCounter[word] + 1
print('{:15}{:3}'.format('Word','Count'))
print('-' * 18)
# printing the words and its occurrence.
for (word,occurance) in wordCounter.items():
print('{:15}{:3}'.format(word,occurance))
Использование параметра Defaultdict:
from collections import defaultdict
def read_file(fname):
words_dict = defaultdict(int)
fp = open(fname, 'r')
lines = fp.readlines()
words = []
for line in lines:
words += line.split(' ')
for word in words:
words_dict[word] += 1
return words_dict
Вы повторяете каждую строку и вызываете счетчик каждый раз. Вы хотите, чтобы Counter запускал весь файл. Попробуйте:
from collections import Counter
with open("TEST.txt", "r"):
contents = f.read().split()
print Counter(contents)
from collections import Counter;
cnt = Counter ();
for line in open ('TEST.txt', 'r'):
for word in line.split ():
cnt [word] += 1
print cnt
Counter.update
и не требует чтения всего файла в памяти ... – Jon Clements♦ 26 February 2013 в 09:00