Hướng dẫn how do you count how many times a word appears in a dictionary python? - làm cách nào để đếm số lần một từ xuất hiện trong từ điển python?

Làm thế nào tôi có thể lấy chương trình đọc qua danh sách các từ và thêm chúng vào từ điển với số lần chúng xảy ra (tôi có chúng trong danh sách có tên w để gọi điện):

words = {}
for ws in w:
  if ws not in words:
    words[ws] = [ws.count()]
  else:
    words[ws].append(ws.count())

Nó rõ ràng không phải là count mà tôi sử dụng ở đây?

Hướng dẫn how do you count how many times a word appears in a dictionary python? - làm cách nào để đếm số lần một từ xuất hiện trong từ điển python?

Yu Hao

Huy hiệu vàng 117K4444 gold badges232 silver badges286 bronze badges

Đã hỏi ngày 18 tháng 5 năm 2015 lúc 7:27May 18, 2015 at 7:27

Có lớp chuyên dụng có tên

import collections
words = "hey hey hello"
c = collections.Counter(words.split())
print c  # Counter({'hey': 2, 'hello': 1})
0 để thực hiện các nhiệm vụ như vậy:

import collections
words = "hey hey hello"
c = collections.Counter(words.split())
print c  # Counter({'hey': 2, 'hello': 1})

Giải pháp rõ ràng sẽ là một cái gì đó như thế này:

wordsCount = {}
words = []  # list of words
for word in words:
  if word not in wordsCount:
    wordsCount[word] = 0
  wordsCount[word] += 1

Đã trả lời ngày 18 tháng 5 năm 2015 lúc 8:25May 18, 2015 at 8:25

Hướng dẫn how do you count how many times a word appears in a dictionary python? - làm cách nào để đếm số lần một từ xuất hiện trong từ điển python?

Łukasz Rogalskiłukasz RogalskiŁukasz Rogalski

21.1k8 Huy hiệu vàng56 Huy hiệu bạc91 Huy hiệu Đồng8 gold badges56 silver badges91 bronze badges

Bạn có thể làm được việc này:

w = ['a', 'b', 'c', 'b', 'd', 'c']

words = {}
for ws in w:
    if ws not in words:
        words[ws] = 1
    else:
        words[ws] += 1

print (words)

Đầu ra là

import collections
words = "hey hey hello"
c = collections.Counter(words.split())
print c  # Counter({'hey': 2, 'hello': 1})
1.

Đã trả lời ngày 18 tháng 5 năm 2015 lúc 8:19May 18, 2015 at 8:19

Hướng dẫn how do you count how many times a word appears in a dictionary python? - làm cách nào để đếm số lần một từ xuất hiện trong từ điển python?

fluency03fluency03fluency03

2.5476 Huy hiệu vàng31 Huy hiệu bạc62 Huy hiệu Đồng6 gold badges31 silver badges62 bronze badges

Một cách khác để làm điều này:

s="There is a jungle nearby our house.We need to go for a walk in jungle"
d={}
sp=s.split(' ')
for item in sp:
    count=sp.count(item)
    d.update({item:count})
print d

Đã trả lời ngày 10 tháng 1 năm 2018 lúc 3:39Jan 10, 2018 at 3:39

1

Cập nhật lần cuối vào ngày 19 tháng 8 năm 2022 21:50:47 (UTC/GMT +8 giờ)

Chuỗi Python: Bài tập-12 với giải pháp

Viết một chương trình Python để đếm các lần xuất hiện của mỗi từ trong một câu nhất định.

Hướng dẫn how do you count how many times a word appears in a dictionary python? - làm cách nào để đếm số lần một từ xuất hiện trong từ điển python?

Giải pháp mẫu:-:-

Mã Python:

def word_count(str):
    counts = dict()
    words = str.split()

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1

    return counts

print( word_count('the quick brown fox jumps over the lazy dog.'))

Đầu ra mẫu:

{'the': 2, 'jumps': 1, 'brown': 1, 'lazy': 1, 'fox': 1, 'over': 1, 'quick': 1, 'dog.': 1} 

Flowchart:

Hướng dẫn how do you count how many times a word appears in a dictionary python? - làm cách nào để đếm số lần một từ xuất hiện trong từ điển python?

Trực quan hóa thực thi mã Python:

Công cụ sau đây trực quan hóa những gì máy tính đang làm từng bước khi nó thực hiện chương trình đã nói:

Trình chỉnh sửa mã Python:

Có một cách khác để giải quyết giải pháp này? Đóng góp mã của bạn (và nhận xét) thông qua Disqus.

Trước đây: Viết chương trình Python để xóa các ký tự có giá trị chỉ mục lẻ của một chuỗi đã cho. Write a Python program to remove the characters which have odd index values of a given string.
Next: Write a Python script that takes input from the user and displays that input back in upper and lower cases.

Python: Lời khuyên trong ngày

Danh sách các thuộc tính đối tượng:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> dir("Hello World")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']