首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取和写入文件

读取和写入文件
EN

Stack Overflow用户
提问于 2016-02-18 07:38:25
回答 2查看 28关注 0票数 0

我正在尝试读取一个文本文件,并将该文件的内容转换为一个新文件上的猪拉丁。这就是我所拥有的:

代码语言:javascript
复制
def pl_line(word):
    statement = input('enter a string: ')

    words = statement.split()

    for word in words:
        if len(word) <= 1:
            print(word + 'ay')
        else:
            print(word[1:] + word[0] + 'ay')


def pl_file(old_file, new_file):
    old_file = input('enter the file you want to read from: ')
    new_file = input('enter the file you would like to write to: ')

    write_to = open(new_file, 'w')
    read_from = open(old_file, 'r')

    lines = read_from.readlines()
    for line in lines():
        line = pl_line(line.strip('\n'))
        write_to.write(line + '\n')
    read_from.close()
    write_to.close()

但是,当我运行此命令时,收到以下错误消息: TypeError:'list‘对象不可调用

对如何改进我的代码有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2016-02-18 10:01:02

以下是对实际转换器的一些改进:

代码语言:javascript
复制
_VOWELS = 'aeiou'
_VOWELS_Y = _VOWELS + 'y'
_SILENT_H_WORDS = "hour honest honor heir herb".split()

def igpay_atinlay(word:str, with_vowel:str='yay'):
    is_title = False
    if word.title() == word:
        is_title = True
        word = word.lower()

    # Default case, strangely, is 'in-yay'
    result = word + with_vowel

    if not word[0] in _VOWELS and not word in _SILENT_H_WORDS:
        for pos in range(1, len(word)):
            if word[pos] in _VOWELS:
                result = word[pos:] + word[0:pos] + 'ay'
                break

    if is_title:
        result = result.title()

    return result

def line_to_pl(line:str, with_vowel:str='yay'):
    new_line = ''

    start = None
    for pos in range(0, len(line)):
        if line[pos].isalpha() or line[pos] == "'" or line[pos] == "-":
            if start is None:
                start = pos
        else:
            if start is not None:
                new_line += igpay_atinlay(line[start:pos], with_vowel=with_vowel)
                start = None
            new_line += line[pos]

    if start is not None:
        new_line += igpay_atinlay(line[start:pos], with_vowel=with_vowel)
        start = None

    return new_line

tests = """
Now is the time for all good men to come to the aid of their party!
Onward, Christian soldiers!
A horse! My kingdom for a horse!
Ng!
Run away!
This is it.
Help, I need somebody.
Oh, my!
Dr. Livingston, I presume?
"""

for t in tests.split("\n"):
    if t:
        print(t)
        print(line_to_pl(t))
票数 2
EN

Stack Overflow用户

发布于 2016-02-18 07:57:26

您很可能将read_fromwrite_to的赋值搞混了,所以无意中试图从一个仅以写访问方式打开的文件中进行读取。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35469951

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档