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

Vì vậy, tôi có một từ điển có chứa công thức nấu ăn. Mã hiện tại của tôi đang kiểm tra xem một chuỗi có tồn tại trong một giá trị hay không thì thêm nó vào bộ đếm. Tuy nhiên, tôi muốn nó để bất cứ khi nào chuỗi gặp trong một giá trị từ điển cộng một vào bộ đếm vì có thể có nhiều lần xuất hiện của cùng một từ trong giá trị và tôi muốn chắc chắn rằng tôi đếm tất cả chúng. Ngay bây giờ mã của tôi để đếm các giá trị trong từ điển là:

        if [token in str[value].lower[]] and [key == 'title']:
            title_c += 1
            
        elif [token in str[value].lower[]] and [key == 'categories']:
            cat_c += 1
            
        elif [token in str[value].lower[]] and [key == 'ingredients']:
            ing_c += 1
            
        elif [token in str[value].lower[]] and [key == 'directions']:
            dire_c += 1

Nó kiểm tra khóa cho từ điển và nếu chuỗi xuất hiện trong giá trị cho khóa đó và nếu nó thêm 1 vào bộ đếm. Tuy nhiên, nếu mã thông báo là 'chuối' nhưng giá trị cho khóa tiêu đề chẳng hạn là 'chuối chuối', nó sẽ thêm 1 vào bộ đếm tiêu đề thay vì 2. Làm thế nào tôi có thể thay đổi nó cho việc này?

Từ điển của tôi chứa một danh sách các công thức nấu ăn. Dưới đây là một ví dụ về một phần dữ liệu trong từ điển. Tìm kiếm của tôi chỉ nhìn qua tiêu đề, danh mục, thành phần và hướng dẫn.

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },

Trong bài đăng này, bạn sẽ học cách sử dụng Python để đếm số lần xuất hiện trong một chuỗi. Bạn sẽ học được bốn cách khác nhau để thực hiện điều này, bao gồm: Phương pháp chuỗi .count[] tích hợp và mô-đun counter tuyệt vời.

Biết cách làm điều này là một kỹ năng cực kỳ hữu ích, cho phép bạn tìm, giả sử, trùng lặp các giá trị trong một chuỗi hoặc xóa các ký tự không mong muốn [như các ký tự đặc biệt].

Giải pháp dễ dàng: Sử dụng chuỗi .count[]

>>> a_string = 'the quick brown fox jumps over the lazy dog'
>>> print[a_string.count['o']]
4

  • Số lần xuất hiện trong một chuỗi với .count []
  • Số lượng xảy ra trong chuỗi Python với bộ đếm
  • Sử dụng các biểu thức thông thường [regex] để đếm các lần xuất hiện trong chuỗi python
  • Sử dụng một vòng lặp để đếm các lần xuất hiện trong chuỗi python
  • Sự kết luận

Trong bài đăng này, bạn đã học cách sử dụng Python để đếm các lần xuất hiện trong một chuỗi bằng bốn phương pháp khác nhau. Cụ thể, bạn đã học cách đếm các lần xuất hiện trong một chuỗi bằng phương pháp .count[] tích hợp, lớp

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
3 từ các bộ sưu tập, phương thức
>>> a_string = 'the quick brown fox jumps over the lazy dog'
>>> print[a_string.count['o']]
4
6 từ biểu thức thông thường ____ ____37, cũng như cách sử dụng một vòng lặp.

Nếu bạn muốn tìm hiểu thêm về lớp

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
3, hãy xem tài liệu chính thức ở đây.

>>> a_string = 'the quick brown fox jumps over the lazy dog'
>>> print['o appears this many times: ', a_string.count['o']]
>>> print['the appears this many times: ', a_string.count['the']]

o appears this many times:  4
ui appears this many times:  2

Trong bài đăng này, bạn sẽ học cách sử dụng Python để đếm số lần xuất hiện trong một chuỗi. Bạn sẽ học được bốn cách khác nhau để thực hiện điều này, bao gồm: Phương pháp chuỗi .count[] tích hợp và mô-đun counter tuyệt vời.

Số lượng xảy ra trong chuỗi Python với bộ đếm

Sử dụng các biểu thức thông thường [regex] để đếm các lần xuất hiện trong chuỗi python

Một trong những cách tích hợp trong đó bạn có thể sử dụng Python để đếm số lần xuất hiện trong chuỗi là sử dụng phương thức chuỗi .count[] tích hợp. Phương thức lấy một đối số, một ký tự hoặc một chuỗi con và trả về số lần ký tự tồn tại trong chuỗi được liên kết với phương thức.

from collections import Counter

a_string = 'the quick brown fox jumps over the lazy dog'
collection = Counter[a_string]

print[collection]

# Returns: Counter[{' ': 8, 'o': 4, 'e': 3, 't': 2, 'h': 2, 'u': 2, 'r': 2, 'q': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'w': 1, 'n': 1, 'f': 1, 'x': 1, 'j': 1, 'm': 1, 'p': 1, 's': 1, 'v': 1, 'l': 1, 'a': 1, 'z': 1, 'y': 1, 'd': 1, 'g': 1}]

Phương pháp này rất đơn giản để thực hiện. Trong ví dụ dưới đây, chúng tôi sẽ tải một chuỗi mẫu và sau đó đếm số lần chỉ là một ký tự và một chuỗi con xuất hiện:

  1. Trong ví dụ trên, bạn đã sử dụng phương thức chuỗi tích hợp .count[] để đếm số lần cả một ký tự duy nhất và một chuỗi xuất hiện trong một chuỗi lớn hơn.
  2. Để tìm ra một cách linh hoạt và hiệu quả hơn để đếm các sự xuất hiện của một ký tự trong chuỗi Python, bạn cũng có thể sử dụng đối tượng
    {
      "title": "\"Blanketed\" Eggplant ",
      "categories": [
       "Tomato",
       "Vegetable",
       "Appetizer",
       "Side",
       "Vegetarian",
       "Eggplant",
       "Pan-Fry",
       "Vegan",
       "Bon App\u00e9tit"
      ],
      "ingredients": [
       "8 small Japanese eggplants, peeled",
       "16 large fresh mint leaves",
       "4 large garlic cloves, 2 slivered, 2 flattened",
       "2 cups olive oil [for deep frying]",
       "2 pounds tomatoes",
       "7 tablespoons extra-virgin olive oil",
       "1 medium onion, chopped",
       "6 fresh basil leaves",
       "1 tablespoon dried oregano",
       "1 1/2 tablespoons drained capers"
      ],
      "directions": [
       "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
       "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
       "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
       "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
       "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
      ],
      "rating": 3.75,
      "calories": 1386.0,
      "protein": 9.0,
      "fat": 133.0
     },
    
    {
      "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
      "categories": [
       "Condiment/Spread",
       "Tomato",
       "Appetizer",
       "Kid-Friendly",
       "Quick & Easy",
       "Lunch",
       "Spring",
       "Summer",
       "Vegetarian",
       "Dairy Free",
       "Peanut Free",
       "Tree Nut Free",
       "Soy Free",
       "Kosher"
      ],
      "ingredients": [
       "1 lemon, zested, juiced",
       "1/2 shallot, finely chopped",
       "1 pound grape tomatoes, halved",
       "2 tablespoons extra-virgin olive oil",
       "1 tablespoon Sherry vinegar",
       "1 teaspoon kosher salt",
       "1 teaspoon freshly ground black pepper",
       "1 teaspoon Worcestershire sauce",
       "1/4 teaspoon cayenne pepper",
       "5 tablespoons finely grated fresh horseradish, divided",
       "2 celery stalks, thinly sliced",
       "3 tablespoons coarsely chopped celery leaves",
       "6 tablespoons mayonnaise",
       "6 slices toasted rye bread"
      ],
      "directions": [
       "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
       "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
      ],
      "rating": 5.0,
      "calories": 189.0,
      "protein": 2.0,
      "fat": 16.0
     },
    
    3 từ mô-đun
    {
      "title": "\"Blanketed\" Eggplant ",
      "categories": [
       "Tomato",
       "Vegetable",
       "Appetizer",
       "Side",
       "Vegetarian",
       "Eggplant",
       "Pan-Fry",
       "Vegan",
       "Bon App\u00e9tit"
      ],
      "ingredients": [
       "8 small Japanese eggplants, peeled",
       "16 large fresh mint leaves",
       "4 large garlic cloves, 2 slivered, 2 flattened",
       "2 cups olive oil [for deep frying]",
       "2 pounds tomatoes",
       "7 tablespoons extra-virgin olive oil",
       "1 medium onion, chopped",
       "6 fresh basil leaves",
       "1 tablespoon dried oregano",
       "1 1/2 tablespoons drained capers"
      ],
      "directions": [
       "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
       "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
       "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
       "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
       "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
      ],
      "rating": 3.75,
      "calories": 1386.0,
      "protein": 9.0,
      "fat": 133.0
     },
    
    {
      "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
      "categories": [
       "Condiment/Spread",
       "Tomato",
       "Appetizer",
       "Kid-Friendly",
       "Quick & Easy",
       "Lunch",
       "Spring",
       "Summer",
       "Vegetarian",
       "Dairy Free",
       "Peanut Free",
       "Tree Nut Free",
       "Soy Free",
       "Kosher"
      ],
      "ingredients": [
       "1 lemon, zested, juiced",
       "1/2 shallot, finely chopped",
       "1 pound grape tomatoes, halved",
       "2 tablespoons extra-virgin olive oil",
       "1 tablespoon Sherry vinegar",
       "1 teaspoon kosher salt",
       "1 teaspoon freshly ground black pepper",
       "1 teaspoon Worcestershire sauce",
       "1/4 teaspoon cayenne pepper",
       "5 tablespoons finely grated fresh horseradish, divided",
       "2 celery stalks, thinly sliced",
       "3 tablespoons coarsely chopped celery leaves",
       "6 tablespoons mayonnaise",
       "6 slices toasted rye bread"
      ],
      "directions": [
       "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
       "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
      ],
      "rating": 5.0,
      "calories": 189.0,
      "protein": 2.0,
      "fat": 16.0
     },
    
    4 tích hợp. Mô -đun cung cấp một số lớp trợ giúp để làm việc, tốt, các bộ sưu tập các mục khác nhau.
  3. Trong trường hợp này, bộ sưu tập của chúng tôi sẽ là một chuỗi:
    {
      "title": "\"Blanketed\" Eggplant ",
      "categories": [
       "Tomato",
       "Vegetable",
       "Appetizer",
       "Side",
       "Vegetarian",
       "Eggplant",
       "Pan-Fry",
       "Vegan",
       "Bon App\u00e9tit"
      ],
      "ingredients": [
       "8 small Japanese eggplants, peeled",
       "16 large fresh mint leaves",
       "4 large garlic cloves, 2 slivered, 2 flattened",
       "2 cups olive oil [for deep frying]",
       "2 pounds tomatoes",
       "7 tablespoons extra-virgin olive oil",
       "1 medium onion, chopped",
       "6 fresh basil leaves",
       "1 tablespoon dried oregano",
       "1 1/2 tablespoons drained capers"
      ],
      "directions": [
       "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
       "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
       "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
       "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
       "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
      ],
      "rating": 3.75,
      "calories": 1386.0,
      "protein": 9.0,
      "fat": 133.0
     },
    
    {
      "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
      "categories": [
       "Condiment/Spread",
       "Tomato",
       "Appetizer",
       "Kid-Friendly",
       "Quick & Easy",
       "Lunch",
       "Spring",
       "Summer",
       "Vegetarian",
       "Dairy Free",
       "Peanut Free",
       "Tree Nut Free",
       "Soy Free",
       "Kosher"
      ],
      "ingredients": [
       "1 lemon, zested, juiced",
       "1/2 shallot, finely chopped",
       "1 pound grape tomatoes, halved",
       "2 tablespoons extra-virgin olive oil",
       "1 tablespoon Sherry vinegar",
       "1 teaspoon kosher salt",
       "1 teaspoon freshly ground black pepper",
       "1 teaspoon Worcestershire sauce",
       "1/4 teaspoon cayenne pepper",
       "5 tablespoons finely grated fresh horseradish, divided",
       "2 celery stalks, thinly sliced",
       "3 tablespoons coarsely chopped celery leaves",
       "6 tablespoons mayonnaise",
       "6 slices toasted rye bread"
      ],
      "directions": [
       "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
       "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
      ],
      "rating": 5.0,
      "calories": 189.0,
      "protein": 2.0,
      "fat": 16.0
     },
    
    5.
  4. Những gì chúng tôi đã hoàn thành trong mã trên là như sau:

Chúng tôi đã nhập

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
3 từ mô -đun bộ sưu tập

Sau đó, chúng tôi đã gán chuỗi của chúng tôi cho biến

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
7

Chúng tôi đã chuyển chuỗi vào một đối tượng

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
3 và gọi nó là
{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
9

Cuối cùng, chúng tôi đã in đối tượng

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
9 mới

>>> print[collection['a']]
>>> print[collection['e']]

1
3

Những gì bạn có thể thấy là những gì mà trả về là một đối tượng đối tượng. Chúng tôi có thể xác nhận điều này bằng cách chạy

>>> a_string = 'the quick brown fox jumps over the lazy dog'
>>> print[a_string.count['o']]
4
1 trả về
>>> a_string = 'the quick brown fox jumps over the lazy dog'
>>> print[a_string.count['o']]
4
2.

Điều tuyệt vời về lớp này là nó chứa một yếu tố giống như từ điển có chứa sự xuất hiện của mọi vật phẩm có thể lặp lại trong mục được truyền vào.

Sử dụng các biểu thức thông thường [regex] để đếm các lần xuất hiện trong chuỗi python

Bạn cũng có thể sử dụng các biểu thức thông thường [regex] để đếm số lần xuất hiện trong chuỗi Python. Cách tiếp cận này là một chút quá mức cần thiết, nhưng nếu bạn quen thuộc với Regex, thì đó có thể là một cách dễ dàng để thực hiện!

Chúng tôi sẽ sử dụng mô -đun biểu thức thông thường, cụ thể là phương thức

>>> a_string = 'the quick brown fox jumps over the lazy dog'
>>> print[a_string.count['o']]
4
6 để tải các chỉ số của nơi xảy ra ký tự hoặc chuỗi con. Cuối cùng, chúng tôi sẽ sử dụng chức năng
>>> a_string = 'the quick brown fox jumps over the lazy dog'
>>> print[a_string.count['o']]
4
7 tích hợp của Python để xem tần suất xảy ra ký tự hoặc chuỗi con.

Hãy để xem cách thức hoạt động của nó:

>>> import re

>>> a_string = 'the quick brown fox jumps over the lazy dog'
>>> print[len[re.findall['o', a_string]]]

4

Chúng ta có thể thấy rằng phương pháp này là một cách làm việc kỳ lạ, đặc biệt là khi so sánh với hai phương pháp ở trên, bao gồm phương pháp .count[] tích hợp và lớp

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
3 tích hợp từ các bộ sưu tập.

Cuối cùng, hãy để Lừa xem cách chúng ta có thể đếm các sự xuất hiện bằng cách sử dụng một vòng lặp.

Sử dụng một vòng lặp để đếm các lần xuất hiện trong chuỗi python

Sử dụng một vòng lặp trong python để đếm các sự xuất hiện trong một chuỗi là một chút của một giải pháp ngây thơ, nhưng đôi khi nó có thể có ích.

Cách nó hoạt động, là các danh sách là các mục mà bạn có thể lặp lại [hoặc, thường được gọi là Iterables], có nghĩa là bạn có thể lặp qua từng ký tự trong một chuỗi và đếm xem một ký tự có xảy ra hay không.

Hãy để thực hiện ví dụ dưới đây và sau đó xem xét cách chúng tôi hoàn thành mọi thứ:

a_string = 'the quick brown fox jumps over the lazy dog'

count_o = 0

for character in a_string:
    if character == 'o':
        count_o += 1
    else:
        pass

print[count_o]

# Returns: 4

Những gì chúng tôi đã làm ở đây là:

  1. Khởi tạo một danh sách mới
  2. Đặt biến
    >>> a_string = 'the quick brown fox jumps over the lazy dog'
    >>> print['o appears this many times: ', a_string.count['o']]
    >>> print['the appears this many times: ', a_string.count['the']]
    
    o appears this many times:  4
    ui appears this many times:  2
    0 thành 0
  3. Lặp qua mỗi
    >>> a_string = 'the quick brown fox jumps over the lazy dog'
    >>> print['o appears this many times: ', a_string.count['o']]
    >>> print['the appears this many times: ', a_string.count['the']]
    
    o appears this many times:  4
    ui appears this many times:  2
    1 trong chuỗi và đánh giá nếu nó bằng với
    >>> a_string = 'the quick brown fox jumps over the lazy dog'
    >>> print['o appears this many times: ', a_string.count['o']]
    >>> print['the appears this many times: ', a_string.count['the']]
    
    o appears this many times:  4
    ui appears this many times:  2
    2. Nếu có, chúng tôi sẽ tăng biến
    >>> a_string = 'the quick brown fox jumps over the lazy dog'
    >>> print['o appears this many times: ', a_string.count['o']]
    >>> print['the appears this many times: ', a_string.count['the']]
    
    o appears this many times:  4
    ui appears this many times:  2
    0 lên 1. Nếu không, chúng tôi không làm gì cả.

Giải pháp này hoạt động, nhưng nó có một chút tẻ nhạt để viết ra và nó không nhanh lắm cho chuỗi lớn hơn.

Sự kết luận

Trong bài đăng này, bạn đã học cách sử dụng Python để đếm các lần xuất hiện trong một chuỗi bằng bốn phương pháp khác nhau. Cụ thể, bạn đã học cách đếm các lần xuất hiện trong một chuỗi bằng phương pháp .count[] tích hợp, lớp

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
3 từ các bộ sưu tập, phương thức
>>> a_string = 'the quick brown fox jumps over the lazy dog'
>>> print[a_string.count['o']]
4
6 từ biểu thức thông thường ____ ____37, cũng như cách sử dụng một vòng lặp.

Nếu bạn muốn tìm hiểu thêm về lớp

{
  "title": "\"Blanketed\" Eggplant ",
  "categories": [
   "Tomato",
   "Vegetable",
   "Appetizer",
   "Side",
   "Vegetarian",
   "Eggplant",
   "Pan-Fry",
   "Vegan",
   "Bon App\u00e9tit"
  ],
  "ingredients": [
   "8 small Japanese eggplants, peeled",
   "16 large fresh mint leaves",
   "4 large garlic cloves, 2 slivered, 2 flattened",
   "2 cups olive oil [for deep frying]",
   "2 pounds tomatoes",
   "7 tablespoons extra-virgin olive oil",
   "1 medium onion, chopped",
   "6 fresh basil leaves",
   "1 tablespoon dried oregano",
   "1 1/2 tablespoons drained capers"
  ],
  "directions": [
   "Place eggplants on double thickness of paper towels. Salt generously. Let stand 1 hour. Pat dry with paper towels. Cut 2 deep incisions in each eggplant. Using tip of knife, push 1 mint leaf and 1 garlic sliver into each incision.",
   "Pour 2 cups oil into heavy medium saucepan and heat to 375\u00b0F. Add eggplants in batches and fry until deep golden brown, turning occasionally, about 4 minutes. Transfer eggplants to paper towels and drain.",
   "Blanch tomatoes in pot of boiling water for 20 seconds. Drain. Peel tomatoes. Cut tomatoes in half; squeeze out seeds. Chop tomatoes; set aside.",
   "Heat 4 tablespoons extra-virgin olive oil in large pot over high heat. Add 2 flattened garlic cloves; saut\u00e9 until light brown, about 3 minutes. Discard garlic. Add onion; saut\u00e9 until translucent, about 5 minutes. Add reduced to 3 cups, stirring occasionally, about 20 minutes.",
   "Mix capers and 3 tablespoons extra-virgin olive oil into sauce. Season with salt and pepper. Reduce heat. Add eggplants. Simmer 5 minutes, spooning sauce over eggplants occasionally. Spoon sauce onto platter. Top with eggplants. Serve warm or at room temperature."
  ],
  "rating": 3.75,
  "calories": 1386.0,
  "protein": 9.0,
  "fat": 133.0
 },

{
  "title": "\"Bloody Mary\" Tomato Toast with Celery and Horseradish ",
  "categories": [
   "Condiment/Spread",
   "Tomato",
   "Appetizer",
   "Kid-Friendly",
   "Quick & Easy",
   "Lunch",
   "Spring",
   "Summer",
   "Vegetarian",
   "Dairy Free",
   "Peanut Free",
   "Tree Nut Free",
   "Soy Free",
   "Kosher"
  ],
  "ingredients": [
   "1 lemon, zested, juiced",
   "1/2 shallot, finely chopped",
   "1 pound grape tomatoes, halved",
   "2 tablespoons extra-virgin olive oil",
   "1 tablespoon Sherry vinegar",
   "1 teaspoon kosher salt",
   "1 teaspoon freshly ground black pepper",
   "1 teaspoon Worcestershire sauce",
   "1/4 teaspoon cayenne pepper",
   "5 tablespoons finely grated fresh horseradish, divided",
   "2 celery stalks, thinly sliced",
   "3 tablespoons coarsely chopped celery leaves",
   "6 tablespoons mayonnaise",
   "6 slices toasted rye bread"
  ],
  "directions": [
   "Combine lemon zest, lemon juice, shallot, tomatoes, oil, vinegar, salt, black pepper, Worcestershire sauce, cayenne, and 1 Tbsp. horseradish in a large bowl. Let marinate 10 minutes, then stir in celery stalks and leaves.",
   "Meanwhile, combine mayonnaise and remaining 4 Tbsp. horseradish in a small bowl. Spread 1 Tbsp. horseradish-mayonnaise on each slice of rye. Top toasts evenly with tomato mixture."
  ],
  "rating": 5.0,
  "calories": 189.0,
  "protein": 2.0,
  "fat": 16.0
 },
3, hãy xem tài liệu chính thức ở đây.

Bài Viết Liên Quan

Chủ Đề