我有一个输入字符串
“ First Last,David Joyner和George Burdell”
我希望输出为格式化字符串:
Last,F.,Joyner,D.和Burdell,G。
更具体地说:
我的代码
<div class="progress-container">
<ol class="progress-bar">
<li class="progress-1 is-active" data-step="1">
<h3>1</h3>
</li>
<li class="progress-2 is-active" data-step="2">
<h3>2</h3>
</li>
<li class="progress-3 is-active" data-step="3">
<h3>3</h3>
</li>
<li class="progress-4 progress__last is-active" data-step="4">
<h3>4</h3>
</li>
</ol>
</div>
预期:
Last,F.,Joyner,D.和Burdell,G。
实际:
Last,F.,Joyner,D。,
省略号条件似乎不正确,因此,输出中缺少&&Burdell,G。
答案 0 :(得分:1)
我使用了列表理解和简单的python字符串拆分方法:
m = "First Last, David Joyner, and George Burdell"
m_splitted = [i.split() for i in m.strip().split(', ') ]
m_formatted =['& '+value[2]+', '+value[2][0]+'.' if index == len(m_splitted)-1 else value[1]+', '+value[0][0]+'.' for index, value in enumerate(m_splitted)]
m_joined = ', '.join(m_formatted)
print(m_joined)
输出:
C:\Users\Documents>py test.py
Last, F., Joyner, D., & Burdell, B.
针对您的方法:
def names_to_apa(mystring):
m_splitted = [i.split() for i in mystring.strip().split(', ') ]
m_formatted =[value[2]+', '+value[2][0]+'.' if index == len(m_splitted)-1 else value[1]+', '+value[0][0]+'.' for index, value in enumerate(m_splitted)]
m_joined = ', '.join(m_formatted)
return m_joined
答案 1 :(得分:0)
您不需要使用奇偶切换。用单个逗号替换, and
后,split(', ')
将返回一个很好的列表,其中包含所有“第一倒数”对。然后,您只需要切换它们即可。
一次执行一个步骤–您可以在任意位置插入print(names)
,以了解每个步骤的作用:
def names_to_apa(names):
names = names.replace(', and ', ', ')
names = names.split(', ')
names = [name.split() for name in names]
names = [name[-1]+', '+(''.join(initial[0]+'.' for initial in name[:-1])) for name in names]
names = ', '.join(names[:-1])+', & '+names[-1]
return names
print (names_to_apa("First Last, M. Night Shamalyam, David Joyner, and George Burdell"))
结果:
Last, F., Shamalyam, M.N., Joyner, D., & Burdell, G.
内部循环理解(''.join(initial[0]+'.' for initial in name[:-1])
处理姓氏之前的所有内容,因此可以有多个缩写。 (当然)如果您有两个姓氏,这将失败。这些需要某种形式的预处理。