繁体   English   中英

将字符串中的每一行转换为字典键

[英]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
  • )关闭非捕获组

正则表达式演示| Python 演示

对于这些匹配项,用空格替换 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)

脚步 -

  1. 通过翻译从字符串中删除标点符号。
  2. 如果单词被 2 \n 字符分隔,则拆分单词
  3. 从列表中删除空格
  4. 删除 \n 字符并使用字典理解生成所需的字典
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM