In một từ trong chuỗi Python

Tôi đang cố gắng tạo danh sách tất cả các từ được phân loại theo chữ cái “m” trong chuỗi của mình nhưng tôi không quản lý để có kết quả dưới dạng danh sách [chỉ loại không xác định hoặc nhiều danh sách]. Tôi muốn sử dụng len. danh sách với kết quả nhưng tôi không thể với kết quả của mình

< wikipedia_text = “Tu viện Liplje là một tu viện Chính thống giáo Serbia dành riêng cho Lễ Truyền tin và nằm ở Đô thị Teslić ở phía bắc Republika Srpska. Nó nằm ở phần rộng nhất của một hẻm núi hẹp mà qua đó một dòng sông nhỏ tên là Bistrica chảy qua. Sự đề cập sớm nhất về tu viện được tìm thấy trong một biên niên sử có từ nửa sau của thế kỷ 15. Các nhà sư của Liplje đã tích cực sao chép các sách tôn giáo trong thế kỷ 17. ” >

thứ nhất =

Input =
def word_letter[x].
danh sách =
cho từ trong x. tách ra[' '].
nếu từ. bắt đầu bằng[“m”] hoặc từ. bắt đầu bằng[“M”].
danh sách. chắp thêm[từ]
in[danh sách]

word_m = word_letter[wikipedia_text]
word_m

đầu ra

['Tu viện']
['Tu viện', 'tu viện']
['Tu viện', 'tu viện', 'Thành phố']
[‘Monastery’, ‘monastery’, ‘Municipality’, ‘mention’]
[‘Monastery’, ‘monastery’, ‘Municipality’, ‘mention’, ‘monastery’]
[‘Monastery’, ‘monastery’, ‘Municipality’, ‘mention’, ‘monastery’, ‘monks’]

cái thứ 2

Đầu vào =

xác định word_letter[x]

cho từ trong x. tách ra[' '].
nếu từ. bắt đầu bằng[“m”] hoặc từ. bắt đầu bằng[“M”].
in [từ]

word_m = word_letter[wikipedia_text]
word_m

Đầu ra =

Tu viện
tu viện
Thành phố
đề cập đến
tu viện
monks

Có ai trong số các bạn có thể giúp tôi việc đó không?
Cảm ơn rất nhiều.

có lẽ,

def word_letter[x]:
  lst = []
  for word in x.split[' '] :
    if word.startswith['m'] or word.startswith['M']:
      lst.append[word]
  return lst
word_m = word_letter[wikipedia_text]
word_m

có thể sử dụng

def word_letter[x]:
  lst = []
  for word in x.split[' '] :
    if any[word.startswith[j] for j in ['m', 'M']]:
      lst.append[word]
  return lst
word_m = word_letter[wikipedia_text]
word_m
1 để tránh lặp lại
def word_letter[x]:
  lst = []
  for word in x.split[' '] :
    if any[word.startswith[j] for j in ['m', 'M']]:
      lst.append[word]
  return lst
word_m = word_letter[wikipedia_text]
word_m
2

def word_letter[x]:
  lst = []
  for word in x.split[' '] :
    if any[word.startswith[j] for j in ['m', 'M']]:
      lst.append[word]
  return lst
word_m = word_letter[wikipedia_text]
word_m

chúng ta cũng có thể sử dụng cách hiểu danh sách ở đây,

def word_letter[x]:
  return [i for i in x.split[' '] if any[i.startswith[j] for j in ['m', 'M']]]
word_m = word_letter[wikipedia_text]
word_m

nếu tên hàm,

def word_letter[x]:
  lst = []
  for word in x.split[' '] :
    if any[word.startswith[j] for j in ['m', 'M']]:
      lst.append[word]
  return lst
word_m = word_letter[wikipedia_text]
word_m
0 không liên quan,

[lambda x: [i for i in x.split[' '] if any[i.startswith[j] for j in ['m', 'M']]]][wikipedia_text]

có thể đổi tên,

[lambda paragraph: [word for word in paragraph.split[' '] if any[word.startswith[character] for character in ['m', 'M']]]][wikipedia_text]

có thể có một cách để làm điều này mà không cần sử dụng các vòng lặp, với sự trợ giúp của việc cắt

tìm thấy một cách sử dụng numpy, nhưng nó hơi lặp đi lặp lại

import numpy as np
x = np.array[wikipedia_text.split[' ']]
list[x[np.char.startswith[x, ['M']]]] + list[x[np.char.startswith[x, ['m']]]]

chúng ta có thể sử dụng

def word_letter[x]:
  lst = []
  for word in x.split[' '] :
    if any[word.startswith[j] for j in ['m', 'M']]:
      lst.append[word]
  return lst
word_m = word_letter[wikipedia_text]
word_m
1,
def word_letter[x]:
  lst = []
  for word in x.split[' '] :
    if any[word.startswith[j] for j in ['m', 'M']]:
      lst.append[word]
  return lst
word_m = word_letter[wikipedia_text]
word_m
2 để giảm sự lặp lại, nhưng số lượng ký tự của mã cao hơn

Viết chương trình Python để in một văn bản dài, chuyển đổi chuỗi thành một danh sách và in tất cả các từ và tần suất xuất hiện của chúng

Giải pháp mẫu

Mã Python

string_words = '''United States Declaration of Independence
From Wikipedia, the free encyclopedia
The United States Declaration of Independence is the statement
adopted by the Second Continental Congress meeting at the Pennsylvania State
House [Independence Hall] in Philadelphia on July 4, 1776, which announced
that the thirteen American colonies, then at war with the Kingdom of Great
Britain, regarded themselves as thirteen independent sovereign states, no longer
under British rule. These states would found a new nation – the United States of
America. John Adams was a leader in pushing for independence, which was passed
on July 2 with no opposing vote cast. A committee of five had already drafted the
formal declaration, to be ready when Congress voted on independence.

John Adams persuaded the committee to select Thomas Jefferson to compose the original
draft of the document, which Congress would edit to produce the final version.
The Declaration was ultimately a formal explanation of why Congress had voted on July
2 to declare independence from Great Britain, more than a year after the outbreak of
the American Revolutionary War. The next day, Adams wrote to his wife Abigail: "The
Second Day of July 1776, will be the most memorable Epocha, in the History of America."
But Independence Day is actually celebrated on July 4, the date that the Declaration of
Independence was approved.

After ratifying the text on July 4, Congress issued the Declaration of Independence in
several forms. It was initially published as the printed Dunlap broadside that was widely
distributed and read to the public. The source copy used for this printing has been lost,
and may have been a copy in Thomas Jefferson's hand.[5] Jefferson's original draft, complete
with changes made by John Adams and Benjamin Franklin, and Jefferson's notes of changes made
by Congress, are preserved at the Library of Congress. The best-known version of the Declaration
is a signed copy that is displayed at the National Archives in Washington, D.C., and which is
popularly regarded as the official document. This engrossed copy was ordered by Congress on
July 19 and signed primarily on August 2.

The sources and interpretation of the Declaration have been the subject of much scholarly inquiry.
The Declaration justified the independence of the United States by listing colonial grievances against
King George III, and by asserting certain natural and legal rights, including a right of revolution.
Having served its original purpose in announcing independence, references to the text of the
Declaration were few in the following years. Abraham Lincoln made it the centerpiece of his rhetoric
[as in the Gettysburg Address of 1863] and his policies. Since then, it has become a well-known statement
on human rights, particularly its second sentence:

We hold these truths to be self-evident, that all men are created equal, that they are endowed by their
Creator with certain unalienable Rights, that among these are Life, Liberty and the pursuit of Happiness.

This has been called "one of the best-known sentences in the English language", containing "the most potent
and consequential words in American history". The passage came to represent a moral standard to which
the United States should strive. This view was notably promoted by Abraham Lincoln, who considered the
Declaration to be the foundation of his political philosophy and argued that it is a statement of principles
through which the United States Constitution should be interpreted.

The U.S. Declaration of Independence inspired many other similar documents in other countries, the first
being the 1789 Declaration of Flanders issued during the Brabant Revolution in the Austrian Netherlands
[modern-day Belgium]. It also served as the primary model for numerous declarations of independence across
Europe and Latin America, as well as Africa [Liberia] and Oceania [New Zealand] during the first half of the
19th century.'''

word_list = string_words.split[]

word_freq = [word_list.count[n] for n in word_list]

print["String:\n {} \n".format[string_words]]
print["List:\n {} \n".format[str[word_list]]]
print["Pairs [Words and Frequencies:\n {}".format[str[list[zip[word_list, word_freq]]]]]

Đầu ra mẫu

def word_letter[x]:
  lst = []
  for word in x.split[' '] :
    if any[word.startswith[j] for j in ['m', 'M']]:
      lst.append[word]
  return lst
word_m = word_letter[wikipedia_text]
word_m
0

Trình bày bằng hình ảnh


Sơ đồ


Trực quan hóa việc 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 thi chương trình nói trên

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?

Trước. Viết chương trình Python để tạo tổ hợp các tổ hợp 3 chữ số.
Tiếp theo. Viết chương trình Python để đếm số lượng từng ký tự của tệp văn bản.

Mức độ khó của bài tập này là gì?

Dễ dàng trung bình khó

Kiểm tra kỹ năng Lập trình của bạn với bài kiểm tra của w3resource



con trăn. Lời khuyên trong ngày

bài tập một phần

Bạn có muốn gán cụ thể một hoặc nhiều phần tử của danh sách và gán tất cả phần còn lại cho một thứ khác không?

Chủ Đề