Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除除每个单词的第一个字母以外的所有字母,并保留标点符号_Python_Python 3.x_Nltk - Fatal编程技术网

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

Python 删除除每个单词的第一个字母以外的所有字母,并保留标点符号,python,python-3.x,nltk,Python,Python 3.x,Nltk,我有一个名为“MyTextFile.txt”的文本文件。我想删除所有的字母并在它们的位置加上破折号,除了每个单词的第一个字母,还保留标点符号 假设文本文件“MyTextFile.txt”包含以下字符串: 男孩去了学校,然后吃了早餐! 哇,这不是一个好故事 预期结果如下所示: T-b-w-T-T-s--,T-a-h-b--! W-,t-,是n-a n-s- 这是我的作品,几乎不错,但并不完美 import nltk file_content = open("MyTextFile.txt", enc

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

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

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

预期结果如下所示:

T-b-w-T-T-s--,T-a-h-b--! W-,t-,是n-a 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 s,T a h b!W,t是n a n 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-at--

并将其应用于文件:

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

这种操作最好使用正则表达式:

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-at--

并将其应用于文件:

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---- ! ?

事实上,@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-

使用简单的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----!?
说明:我使用txt和txt[1:]即从第二个字符开始的txt,然后使用zip创建单个iterable,每个元素由两个字符组成:prev,即previous和curr,即current,如果两者都是我生成的字母,否则为current字符,则我将生成的所有字符合并,并添加第一个字符txt[0]因为它没有以前的版本,所以在一开始就被认为是早期版本


我认为正则表达式更适合这项任务,但是给出上面的示例,我想说明,使用python语言,您可以编写简洁的代码,而无需使用正则表达式。

注意,为了完成这项任务,您需要知道前面的字符-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----!?
说明:我使用txt和txt[1:]即从第二个字符开始的txt,然后使用zip创建单个iterable,每个元素由两个字符组成:prev,即previous和curr,即current,如果两者都是我生成的字母,否则为current字符,则我将生成的所有字符合并,并添加第一个字符txt[0]因为它没有以前的版本,所以在一开始就被认为是早期版本


我认为正则表达式更适合这个任务,但是给出上面的示例,我想展示一下,使用python语言,您可以编写简洁的代码,而无需使用正则表达式。。。哇!您可以在文件而不是字符串上执行此代码吗。我对编程非常陌生,对正则表达式也有一些肤浅的了解:@AkbarHussein只需将txt更改为标记,并在您自己的代码的打印标记之后添加这组代码。@uri goren您的代码工作得非常好,但为了理解它,最后一行之前的那行。。。这里的lambda函数是什么意思??。。。我的意思是这部分[lambda m:m[1]+-*lenm[2]]在正则表达式中有两个捕获群,m[1]是第一个。。。哇!您可以在文件而不是字符串上执行此代码吗。我对编程非常陌生,对正则表达式也有一些肤浅的了解:@AkbarHussein只需将txt更改为标记,并在您自己的代码的打印标记之后添加这组代码。@uri goren您的代码工作得非常好,但为了理解它,最后一行之前的那行。。。这里的lambda函数是什么意思??。。。我的意思是这部分[lambda m:m[1]+-*lenm[2]]正则表达式中有两个捕获组,m[1]是第一个它假设每个单词的第一个字母是alpha,但是你可以在函数keepPuncx中调整它,通过修改temp和进一步的逻辑一点。它假设每个单词的第一个字母是alpha,但是你可以在函数keepPuncx中调整它,通过修改温度和进一步的逻辑位。