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

代码效果

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

相关推荐
用户8356290780512 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780514 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠9 小时前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3109 小时前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫10 小时前
python环境|conda安装和使用(2)
后端·python
程序员龙叔1 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780511 天前
使用 Python 操作 Word 内容控件
后端·python
LDR0061 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术1 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园1 天前
C++20 Modules 模块详解
java·开发语言·spring