就像标题上说的...
我正在尝试编写以下功能:
这里是到目前为止我尝试过的一些代码:
with open('text') as infile:
text = infile.read()
def clean_text_func(text):
punctuation = '!@#$%^&*()_-+={}[]:;"\'|<>,.?/~`'
for marker in punctuation:
text = text.replace(marker, '')
return text
clean_text = clean_text_func(text)
firstwords = [line.split(' ')[0] for line in clean_text.split('\n')]
for word in firstwords:
print(word[0])
这给了我文本文件中每行的第一个字母,与我想要的接近。因此,现在如何将每个字母添加到新字符串中?
您真的很接近解决方案。要获得第一个字母,您只需使用其他切片操作即可获得第一个单词的第一个字符,即:]
first_letters = [line.split(' ')[0][0] for line in clean_text.split('\n')]
注意[0]
之后的额外line.split(' ')[0]
。
这将为您提供第一个字母的列表。要将其放回字符串,只需在空字符串上使用str.join()
,即:
str.join()
请注意,这对于不同长度的字符串也适用(当然会有不同的输出),例如:
''.join(first_letters)