Python练习12

Python日常练习

题目:

试题文件夹下的文本文件sentences.txt中,每行对应一个句子,该句子包含了多个

单词,单词之间以空格隔开。每个单词仅包含英文字母。我们希望能够将文件中的

每个句子转换为"山羊语"。句子的每个单词首先按照下述规则转换:

如果该单词以小写或者大写的元音字母(a, e, i, o, u)开头,则在单词尾部添

加"ma"。比如单词"apple"变为"applema"。

如果该单词以非元音字母开始,则去掉该单词的第一个字母,将该字母附加到单词

尾部,然后附加"ma"。比如"goat"变为"oatgma"。

对于每个句子中的单词,首先按照上述规则转换,然后在该单词之后添加多个字

母'a'。每个单词添加的字母'a'的个数等于其在句子中的序数,即第1个单词后

附加1个'a',第2个单词附加2个'a'... 最后的输出由转换后的单词组成,单词之

间以一个空格隔开。

sentences.txt文本文件中的前两行为:

I speak Goat Latin

The quick brown fox jumped over the lazy dog

程序的输出中前面两行为:

Imaa peaksmaaa oatGmaaaa atinLmaaaaa

heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa

hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa

代码实现

python 复制代码
########## code start ##########
filenameczj='sentences.txt'
def createfileczj():
    tt='''I speak Goat Latin. The quick brown fox jumped over the lazy dog '''
    fczj=open(filenameczj,"w")
    fczj.write(tt)
    fczj.close()
def convert(word):
    if word[0] not in 'aeiouAEIOU':
        word = word[1:] + word[:1]
    return word + 'ma'

createfileczj()
with open('sentences.txt') as f:
    while True:
        line = f.readline()
        if not line:
            break
        words = line.split()
        convert_words = []
        for i, word in enumerate(words, 1):
            convert_words.append(convert(word) + 'a' * i)
        print(' '.join(convert_words))
########## code end ##########

代码效果

有趣的代码需要多加练习!

相关推荐
用户8356290780515 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780515 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生13 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师14 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码14 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf14 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python