如何从单词列表中提取第一个字母并将其组合为单个字符串

问题描述 投票:-3回答:1

就像标题上说的...

我正在尝试编写以下功能:

  1. 采用每行的第一个字母
  2. 将其添加到字符串中
  3. 理想情况下也清除文本(删除标点符号等)

这里是到目前为止我尝试过的一些代码:

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])

这给了我文本文件中每行的第一个字母,与我想要的接近。因此,现在如何将每个字母添加到新字符串中?

python python-3.x text-processing
1个回答
0
投票

您真的很接近解决方案。要获得第一个字母,您只需使用其他切片操作即可获得第一个单词的第一个字符,即:]

first_letters = [line.split(' ')[0] for line in clean_text.split('\n')]

((请注意[0]之后的多余的line.split(' ')[0]

一种更简单的方法是按原样切片line

first_letters = [line[0] for line in clean_text.split('\n')]

一旦您的首字母为list(或实际上为字符串的任何list),您只需将str.join()用于空字符串即可将其放回单个字符串,即:

str.join()
© www.soinside.com 2019 - 2024. All rights reserved.