[英]Convert every line in the string into dictionary key
嗨,我是 python 的新手,不知道我是否可以在這個網站上問這個基本問題
我想將字符串中的每一行轉換為一個鍵並將 0 分配為一個值
我的字符串是:
s = '''
sarika
santha
#
akash
nice
'''
我曾嘗試過這種https://www.geeksforgeeks.org/ways-to-convert-string-to-dictionary/方法,但認為對我的要求沒有用
請幫助任何人提前謝謝
編輯:
實際上我要求的是基本字符串,但我實際上是要跟隨的字符串
s="""
san
francisco
Santha
Kumari
this one
"""
Here it should take {sanfrancisco:0 , santha kumari:0 , this one: 0 }
這是我面臨的挑戰
在我的字符串中,如果有超過 1 個新行間隙,它應該將下一行字符串作為一個單詞並轉換為鍵
您可以通過以下方式進行操作:
>>> s="""
... hello
... #
... world
...
... vk
... """
>>> words = s.split("\n")
>>> words
['', 'hello', '#', 'world', '', 'vk', '']
>>> words = words[1:len(words)-1]
>>> words
['hello', '#', 'world', '', 'vk']
>>> word_dic = {}
>>> for word in words:
... if word not in word_dic:
... word_dic[word]=0
...
>>> word_dic
{'': 0, 'world': 0, '#': 0, 'vk': 0, 'hello': 0}
>>>
如果您有任何問題,請告訴我。
您可以連續匹配所有行后跟 2 個換行符,或者匹配所有行后跟一個換行符。
^(?:\S.*(?:\n\n\S.*)+|\S.*(?:\n\S.*)*)
模式匹配
^
字符串開頭(?:
非捕獲組
\S.*
匹配非空白字符和該行的 rest(?:\n\n\S.*)+
重復匹配 1+ 次 2 個換行符、一個非空白字符和該行的 rest|
或者\S.*
匹配單個非空白字符和該行的 rest(?:\n\S.*)*
可選匹配換行符、非空白字符和行的 rest)
關閉非捕獲組對於這些匹配項,用空格替換 2 個換行符並用空字符串替換一個換行符。
然后從這些值中,創建一個字典並用 0 初始化所有值。
例子
import re
s="""
san
francisco
Santha
Kumari
this one
"""
pattern = r"^(?:\S.*(?:\n\n\S.*)+|\S.*(?:\n\S.*)*)"
my_dict = dict.fromkeys(
[
re.sub(
r"(\n\n)|\n",
lambda n: " " if n.group(1) else "", s.lower()
) for s in re.findall(pattern, s, re.MULTILINE)
],
0
)
print(my_dict)
Output
{'sanfrancisco': 0, 'santha kumari': 0, 'this one': 0}
你可以這樣做:
# Split the string into a list
l = s.split()
dictionary = {}
# iterate through every element of the list and assign a value of 0 to it
n = 0
for word in l:
while n < len(l) - 1:
if word == "#":
continue
w = l[n] + l[n+1]
dictionary.__setitem__(w, 0)
n+=2
print(dictionary)
腳步 -
import string
s = '''
sarika
santha
#
akash
nice
'''
s = s.translate(str.maketrans('', '', string.punctuation))
word_list = s.split('\n\n')
while '' in word_list:
word_list.remove('')
result = {word.replace('\n', ''): 0 for word in word_list}
print(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.