我正试图从一段结构化文本中创建一本词典,但我无法理解正确的语法
text = 'english (fluently), spanish (poorly)'
# desired output:
{english: fluently, spanish: poorly}
# one of my many attempts:
dict((language,proficiency.strip('\(\)')) for language,proficiency in lp.split(' ') for lp in text.split(', '))
# but resulting error:
NameError: name 'lp' is not defined
我猜lp.split(“”)中的lp没有定义,但我不知道如何修改语法以获得所需的结果
事实上,情况更为复杂。我有一个dataframe,我的目标是最终使用一个函数将上述数据整理成每种语言的列和每种相应语言的列。如下所示(尽管可能可以更有效地完成)
# pandas dataframe
pd.DataFrame({'language': ['english, spanish (poorly)', 'turkish']})
# desired output:
pd.DataFrame({'Language: English': [True, False], 'Language proficiency: English': ['average', pd.NA], 'Language: Spanish': [True, False], 'Language proficiency: Spanish': ['poorly', pd.NA], 'Language: Turkish': [False, True], 'Language proficiency: Turkish': [pd.NA, 'average']})
# my attempt
def tidy(content):
if pd.isna(content):
pass
else:
dict((language,proficiency.strip('\(\)')) for language,proficiency in lp.split(' ') for lp in text.split(', '))
def tidy_language(language, content):
if pd.isna(content):
return pd.NA
else:
if language in content.keys():
return True
else:
return False
def tidy_proficiency(language, content):
if pd.isna(content):
return pd.NA
else:
if language in content.keys():
return content.language
else:
return pd.NA
languages = ['english', 'spanish', 'turkish']
df['language'] = df['language'].map(lambda x: tidy(x))
for language in languages:
df['Language: {}'.format(language.capitalize())] = df['language'].map(lambda x: tidy_language(language, content)
df['Language proficiency: {}'.format(language.capitalize())] = df['language'].map(lambda x: tidy_proficiency(language, content)
这里有一个快速的解决方案。将文本馈送到函数
您需要反转列表理解中的两个
for
循环(for
循环需要以与编写命令式代码相同的顺序出现)在
.strip('\(\)')
中不需要反斜杠for language,proficiency in lp.split(' ')
将尝试将lp.split(' ')
的每个项解压到元组(language,proficiency)
,因此,将lp.split(' ')
包装到一个单元素列表中以实现您想要的:以上内容可以写成
dict
理解:读起来好一点
使用
re
的替代方法:虽然fferri为我的原始问题提供了一些完美的解决方案,但我在数据框架上下文中的最终解决方案更像SuperNoob的建议
我的最终解决方案:
相关问题 更多 >
编程相关推荐