2013-11-24 1 views
4

이 같은 주어진 사전이있는 경우 : 나는 새로운 행에 각 키 - 값 출력을 어떻게새 줄에 사전 인쇄의 각 키 - 값을 만드는 방법은 무엇입니까?

{'avglen': 4.419354838709677, 'count:': 93, 'mosts:': 'your', 'longs:': ['stretched'], 'shorts:': ['i', 'a'],} 

를?

잘 길지만 여기에이 사전을 가져 오기 위해 사용하는 코드가 있습니다. 나는 각 키 - 값을 사전에 추가했다. 그래서 나는 가장 짧은 단어를 알아 낸 다음 그 단어를 사전에 추가했습니다. 나는 여분의 콜론이 있다는 것을 알아 차렸다. 하지만 그 값의 일부분을 생각하고 그것을 제거하는 데 .replace()를 사용할 수 있습니까 ??

def build_report(freq): 
    report={} 
    freq_list=list(freq.keys()) 
    keys=sorted(freq, key=len) 
    #for shorts: 
    shortest=keys[0] 
    shortest = [keys[0]] 
    for key in keys[1:]: 
     if len(key) == len(shortest[0]): 
      shortest.append(key) 
     else: 
      break 
    report["shorts:"]=shortest 
    #for longs: 
    longest=keys[-1] 
    longest = [keys[-1]] 
    for key in reversed(keys[:-1]): 
     if len(key) == len(longest[0]): 
      longest.append(key) 
     else: 
      break 
    report["longs:"]=longest 
    #for mode: 
    val_list=list(freq.values()) 
    sorted_val_list=sorted(val_list) 
    mode=sorted_val_list[-1] 
    for key in freq.keys(): 
     if freq[key]==mode: 
      mode_word=key 
    report["mosts:"]=mode_word 
    # for word count: 
    wordcount=len(list(freq.keys())) 
    report["count:"]=wordcount 
    #for average length: 
    avg=list(freq.keys()) 
    average=sum(map(len,avg))/len(avg) 
    report["avglen"]=average 
    #for freq dictionary of word to word count 
    freqs=freq 
    report["freqs:"]=freqs 
    return report 
+0

키에 남은 콜론이있는 것처럼 보입니다. 나는 그 사전을 생성하기 위해 당신이하고있는 것을 보았습니다. – DSM

+0

@DSM 사전을 생성하는 코드를 추가했습니다 – user2976821

답변

12

, 당신은 할 수 :

print("{" + "\n".join("{}: {}".format(k, v) for k, v in d.items()) + "}") 
+3

이제 아름답게 추한 파이썬 라인이 있습니다. :) – samrap

3

으로 반복 dict.items 이상 및 인쇄 :

>>> d = {'avglen': 4.419354838709677, 'count:': 93, 'mosts:': 'your', 'longs:': ['stretched'], 'shorts:': ['i', 'a'],} 
>>> for k, v in d.items(): 
...  print (k, '-->', v) 
...  
mosts: --> your 
count: --> 93 
avglen --> 4.41935483871 
shorts: --> ['i', 'a'] 
longs: --> ['stretched'] 

또는 pprint 모듈을 사용

>>> import pprint 
>>> pprint.pprint(d) 
{'avglen': 4.419354838709677, 
'count:': 93, 
'longs:': ['stretched'], 
'mosts:': 'your', 
'shorts:': ['i', 'a']} 
+0

아무것도 가져 오지 않고 할 수있는 방법이 있습니까?. 첫 번째 것은 사전으로 반환하지 않습니다. – user2976821

4

당신은 pprint 찾고있을 수도, 예쁜 프린터 표준 라이브러리. 예를 들면 : 당신이 정말로 pprint을 가져올 있지만 사전 "처럼"하지 않으려면

import pprint 
pprint.pprint({'avglen': 4.419354838709677, 
       'count:': 93, 
       'mosts:': 'your', 
       'longs:': ['stretched'], 
       'shorts:': ['i', 'a'],}) 

출력

{'avglen': 4.419354838709677, 
'count:': 93, 
'longs:': ['stretched'], 
'mosts:': 'your', 
'shorts:': ['i', 'a']} 
0

지난 여섯 가지 질문에서이 가난한 사전을 텍스트 색인화 된 객체로 사용하는 것 같습니다. 왜 그것을 적절한 수업으로 만들지 않겠습니까?

from collections import Counter 

textfreq = { 
    'I': 1, 'heaven': 1, 'filled': 1, 'their': 1, 'termed': 1, 'of': 4, 
    'And': 3, 'parts': 1, 'neer': 1, 'to': 2, 'song': 1, 'poets': 1, 
    'The': 1, 'a': 2, 'were': 2, 'verse': 1, 'your': 6, 'knows': 1, 
    'not': 1, 'half': 1, 'number': 1, 'but': 1, 'yours': 1, 'come': 2, 
    'rage': 1, 'age': 2, 'Though': 1, 'men': 1, 'fresh': 1, 'heavenly': 1, 
    'say': 1, 'alive': 1, 'truth': 1, 'this': 1, 'If': 2, 'than': 1, 
    'old': 1, 'believe': 1, 'Which': 1, 'that': 1, 'You': 1, 'faces': 1, 
    'yet': 1, 'poet': 1, 'in': 4, 'life': 1, 'most': 1, 'earthly': 1, 
    'will': 1, 'hides': 1, 'my': 3, 'papers': 1, 'is': 1, 'stretched': 1, 
    'rights': 1, 'eyes': 1, 'it': 3, 'yellowed': 1, 'Such': 1, 'So': 1, 
    'all': 1, 'lies': 1, 'the': 1, 'an': 1, 'as': 1, 'write': 1, 
    'child': 1, 'deserts': 1, 'shows': 1, 'tongue': 1, 'twice': 1, 
    'Be': 1, 'high': 1, 'some': 1, 'could': 1, 'should': 2, 'and': 2, 
    'touched': 1, 'like': 1, 'would': 1, 'Who': 1, 'tomb': 1, 'numbers': 1, 
    'antique': 1, 'scorned': 1, 'metre': 1, 'time': 2, 'touches': 1, 
    'be': 1, 'with': 2, 'true': 1, 'beauty': 1, 'rhyme': 1, 'less': 1, 
    'But': 1, 'graces': 1, 'live': 1 
} 

class TextStats(): 
    def __init__(self, text=''): 
     if hasattr(text, 'wordfreq'): 
      # copy an existing TextStats object 
      self.wordfreq = Counter(text.wordfreq) 
     elif hasattr(text, 'keys'): 
      # load from an existing dict or Counter 
      self.wordfreq = Counter(text) 
     else: 
      # parse from a string 
      # TO DO - strip all punctuation 
      self.wordfreq = Counter(w for w in text.lower().split() if w) 

    @classmethod 
    def from_file(cls, fname): 
     with open(fname) as inf: 
      text = ' '.join(line.strip() for line in inf.readlines()) 
      return cls(text.translate(None, '`[email protected]#$\'"')) 

    def __add__(self, otherTextStats): 
     return TextStats(self.wordfreq + otherTextStats.wordfreq) 

    def __str__(self): 
     return(
      "Count:  {}\n" 
      "Average len: {:0.4f}\n" 
      "Shortest:  {}\n" 
      "Most common: {}\n" 
      "Longest:  {}\n".format(
       self.total_words, 
       self.average_word_length, 
       self.shortest_words, 
       self.most_common_words, 
       self.longest_words 
      ) 
     ) 

    @property 
    def unique_words(self): 
     return len(self.wordfreq) 

    @property 
    def total_words(self): 
     return sum(self.wordfreq.values()) 

    @property 
    def total_letters(self): 
     return sum(len(w)*c for w,c in self.wordfreq.items()) 

    @property 
    def average_word_length(self): 
     return float(self.total_letters)/self.total_words 

    @property 
    def shortest_words(self): 
     minlen = len(min(self.wordfreq, key=len)) 
     return sorted(w for w in self.wordfreq if len(w)==minlen) 

    @property 
    def most_common_words(self): 
     most_common = self.wordfreq.most_common() 
     howmany = most_common[0][1] if most_common else 0 
     return sorted(w for w,c in most_common if c == howmany) 

    @property 
    def longest_words(self): 
     maxlen = len(max(self.wordfreq, key=len)) 
     return sorted(w for w in self.wordfreq if len(w)==maxlen) 

def main(): 
    t = TextStats(textfreq) 
    u = TextStats.from_file('corpus.txt') 
    v = t + u 

    print(t) 
    print() 
    print(u) 
    print() 
    print(v) 

if __name__=="__main__": 
    main() 
관련 문제