首页 > 解决方案 > 如何使用函数从 python 中的字符串中删除撇号?

问题描述

我需要创建一个函数 remove_apos() 函数,它有一个字符串作为参数,并返回一个字符串中删除了任何撇号的字符串。这些应该被删除,以便只计算一个单词中的字母。例如,单词“NASA's”应该被视为“NASAs”并且长度为5。我的函数的目标输出是:

Enter name of file:
cassini.txt
File to be processed is:  cassini.txt
The number of words is:    231
The average length of a word is:   5.34

到目前为止我的代码:

# Define your functions here

if __name__ == '__main__':

    # Prompt the user for the name of the file and open it for reading
    input = input('Enter name of file:\n')
    print('File to be processed is: {}'.format(input))

    # Open the file for reading here

    my_file = open(input) 

    line = my_file.read()
    words = line.split()

    add = 0
    count = 0
    for word in words:
        word_wo_punc = "".join([x for x in word if x.isalpha() or x in ("-")])
        add = add + len(word_wo_punc)
        if len(word_wo_punc) > 0:
            count = count + 1
    avg = add/count


    print('The number of words is: {}'.format(count))
    print('The average length of a word is: {:.2f}'.format(avg))

我试图把这部分放在一个函数中:

add = 0
count = 0
for word in words:
    word_wo_punc = "".join([x for x in word if x.isalpha() or x in ("-")])
    add = add + len(word_wo_punc)
    if len(word_wo_punc) > 0:
        count = count + 1
avg = add/count

但似乎没有任何效果,或者我无法弄清楚如何正确返回 word_wo_punc。我想知道如何从 python 中的字符串中删除撇号,以及如何在函数中对其进行编码以便我可以调用它?

标签: python

解决方案


没有任何依赖,使用str.replace

txt = "NASA's"
print(txt.replace("'", ""))

输出:NASAs


推荐阅读