如何定义一个函数来读取文本文件,并返回其所有行的首字母的字符串(python)

问题描述 投票:-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][0] for line in clean_text.split('\n')]

注意[0]之后的额外line.split(' ')[0]

这将为您提供第一个字母的列表。要将其放回字符串,只需在空字符串上使用str.join(),即:

str.join()

请注意,这对于不同长度的字符串也适用(当然会有不同的输出),例如:

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