python - 如何使用函数从 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 中的字符串中删除撇号,以及如何在函数中对其进行编码以便我可以调用它?
解决方案
没有任何依赖,使用str.replace
:
txt = "NASA's"
print(txt.replace("'", ""))
输出:NASAs
推荐阅读
- excel - 无法弄清楚如何编写 VBA 脚本通过将颜色移动到顶部来对列进行排序
- python - 有没有办法通过不和谐邀请获得公会ID?
- javascript - 显示来自 API 的 id 的总和值
- spring-boot - Debezium 无法连接到 SqlServer 2016
- rust - 使用 Rodio crate 找不到文件
- graphics - 如何使用 TouchGFX 帧缓冲区仅镜像 x 轴
- angularjs - Angular Hybrid 应用程序不部署 html 文件
- c# - 通过 Linq 表达式的 foreach 显示所有项目
- sql - 在 postgreSQL 中选择第一个日期
- android - BLE ScanRecord 的 getServiceData 包含什么?