删除每个单词除第一个字母外的所有字母并保留标点符号

Delete all letters except the first letter of each word and keep punctuation

我有一个名为“MyTextFile.txt”的文本文件。我想删除所有字母并在它们的位置放置破折号除了每个单词的第一个字母,还保留标点符号

假设文本文件“MyTextFile.txt”包含以下字符串:

孩子去了学校,然后吃早饭了! 哇,这不是一个好故事吗!?

想要的结果是这样的:

T-- b-- w-- t- t-- s----- , t-- a-- h-- b------ ! W-- , t--- 的 n-- 一个 n--- s---- ! ?

这是我的作品,差不多不错,但还不够完美!

import nltk
file_content = open("MyTextFile.txt", encoding='utf8').read()
tokens = nltk.word_tokenize(file_content)
print(tokens)

first_letter = [i[0] for i in tokens]

new_words = ' '.join(first_letter).strip()
print(new_words)
appendFile = open('results_file.txt', 'w', encoding='utf8')
appendFile.write(new_words)

我的输出是这样的:

T b w t t s , t a h b ! W , t’s nan s ! ?

这种操作最好用正则表达式来完成:

import re
txt = "This is a test!"
dashed = re.sub(r"([A-Za-z])([A-Za-z]+)", lambda m: m[1] + "-"*len(m[2]), txt)
print (dashed)

将输出:T--- i- a t---!

并将其应用于文件:

with open("input_file.txt", 'r') as i:
    with open("output_file.txt", 'w') as o:
        for txt in i:
            dashed = re.sub(r"([A-Za-z])([A-Za-z]+)", lambda m: m[1] + "-"*len(m[2]), txt)
            o.write(dashed + '\n')

实际上,@Uri 的回答比我的好多了。无论如何,它在这里:)

import nltk

file_content = "The boy went to the school, then ate his breakfast! Wow, that’s not a nice story!?"
tokens = nltk.word_tokenize(file_content)
print(tokens)

new_words = []
for token in tokens:
    token = token.strip() 
    if token.isalpha():
        new_word = token[0]
        new_word += "-"*(len(token)-1)
    else:
        new_word = token
    new_words.append(new_word)

new_words = ' '.join(new_words)
print(new_words)
# T-- b-- w--- t- t-- s----- , t--- a-- h-- b-------- ! W-- , t--- ’ s n-- a n--- s---- ! ?

使用简单的 python 逻辑::

def keepPunc(x):
    temp = x[0]
    for i in range(1,len(x)):
        if x[i].isalpha():
            temp=temp+"-"
        else:
            temp=temp+x[i]
    return temp



def func(a):
    temp = a.split()
    final = [i[0]+"-"*(len(i)-1) if i.isalpha() else keepPunc(i)for i in temp]
    print(a)
    print(' '.join(final))

a = "The boy went to the school, then ate his breakfast! Wow, that’s not a nice story!?"
func(a)

输出::

男孩去了学校,然后吃了早餐!哇,这不是一个好故事吗!?

T-- b-- w--- t- t-- s-----, t--- a-- h-- b--------! W--, t---'- n-- a n--- s----!?

请注意,您需要知道前一个字符才能完成该任务 - zip 会有所帮助:

txt = "The boy went to the school, then ate his breakfast! Wow, that’s not a nice story!?"
new_txt = txt[0] + ''.join('-' if curr.isalpha() and prev.isalpha() else curr for prev, curr in zip(txt,txt[1:]))
print(new_txt)

输出:

T-- b-- w--- t- t-- s-----, t--- a-- h-- b--------! W--, t---- n-- a n--- s----!?

说明:我采用 txttxt[1:] 是从第二个字符开始的 txt 然后使用 zip 创建单个可迭代对象,每个元素由两个字符组成:prev 即前一个和 curr 即当前,如果两者都是我制作的字母 - 否则是当前字符,那么我加入我制作的所有字符并在开始时添加第一个字符 (txt[0])考虑的比较早,因为没有previous.

我认为正则表达式更适合这个任务,但是我想通过上面的例子来证明使用 python 语言,你可以编写简洁的代码来完成它而无需使用正则表达式。