用文件中的数字替换罗马数字- Python- typ

2024-06-09 19:49:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取一个文件,然后对于文件中的每个罗马数字,替换为正确的数值(仅适用于数字1-7),然后将文件(所有文本和数字都更改)保存到新文件中。在

我已经打印了下面的代码,但我一直收到这个错误:

'line 4, in new_sonnet
for char in s: 
TypeError: builtin_function_or_method' object is not iterable`

文件保存不正确。 我的代码在下面。文本文件只包含7首莎士比亚十四行诗,用罗马数字隔开。在

^{pr2}$

这是我正在阅读的文件:(我为长度感到抱歉)我无法编辑它。在

I.

From fairest creatures we desire increase,
 That thereby beauty's rose might never die,
 But as the riper should by time decease,
 His tender heir might bear his memory:
 But thou contracted to thine own bright eyes,
 Feed'st thy light's flame with self-substantial fuel,
 Making a famine where abundance lies,
 Thy self thy foe, to thy sweet self too cruel:
 Thou that art now the world's fresh ornament,
 And only herald to the gaudy spring,
 Within thine own bud buriest thy content,
 And, tender churl, mak'st waste in niggarding:
 Pity the world, or else this glutton be,
 To eat the world's due, by the grave and thee.



II.

When forty winters shall besiege thy brow,
 And dig deep trenches in thy beauty's field,
 Thy youth's proud livery so gazed on now,
 Will be a totter'd weed of small worth held: 
 Then being asked, where all thy beauty lies,
 Where all the treasure of thy lusty days; 
 To say, within thine own deep sunken eyes,
 Were an all-eating shame, and thriftless praise.
 How much more praise deserv'd thy beauty's use,
 If thou couldst answer 'This fair child of mine
 Shall sum my count, and make my old excuse,'
 Proving his beauty by succession thine!
 This were to be new made when thou art old,
 And see thy blood warm when thou feel'st it cold.



III.

Look in thy glass and tell the face thou viewest
 Now is the time that face should form another;
 Whose fresh repair if now thou not renewest,
 Thou dost beguile the world, unbless some mother.
 For where is she so fair whose uneared womb
 Disdains the tillage of thy husbandry?
 Or who is he so fond will be the tomb
 Of his self-love, to stop posterity? 
 Thou art thy mother's glass and she in thee
 Calls back the lovely April of her prime;
 So thou through windows of thine age shalt see,
 Despite of wrinkles, this thy golden time.
 But if thou live, remembered not to be,
 Die single and thine image dies with thee.



IV.

Unthrifty loveliness, why dost thou spend
 Upon thy self thy beauty's legacy?
 Nature's bequest gives nothing, but doth lend,
 And being frank she lends to those are free:
 Then, beauteous niggard, why dost thou abuse
 The bounteous largess given thee to give?
 Profitless usurer, why dost thou use
 So great a sum of sums, yet canst not live?
 For having traffic with thy self alone,
 Thou of thy self thy sweet self dost deceive:
 Then how when nature calls thee to be gone,
 What acceptable audit canst thou leave?
 Thy unused beauty must be tombed with thee,
 Which, used, lives th' executor to be.



V.

Those hours, that with gentle work did frame
 The lovely gaze where every eye doth dwell,
 Will play the tyrants to the very same
 And that unfair which fairly doth excel;
 For never-resting time leads summer on
 To hideous winter, and confounds him there;
 Sap checked with frost, and lusty leaves quite gone,
 Beauty o'er-snowed and bareness every where:
 Then were not summer's distillation left,
 A liquid prisoner pent in walls of glass,
 Beauty's effect with beauty were bereft,
 Nor it, nor no remembrance what it was:
 But flowers distilled, though they with winter meet,
 Leese but their show; their substance still lives sweet.



VI.

Then let not winter's ragged hand deface,
 In thee thy summer, ere thou be distilled:
 Make sweet some vial; treasure thou some place
 With beauty's treasure ere it be self-killed.
 That use is not forbidden usury,
 Which happies those that pay the willing loan;
 That's for thy self to breed another thee,
 Or ten times happier, be it ten for one;
 Ten times thy self were happier than thou art,
 If ten of thine ten times refigured thee:
 Then what could death do if thou shouldst depart,
 Leaving thee living in posterity?
 Be not self-willed, for thou art much too fair
 To be death's conquest and make worms thine heir.



VII.

Lo! in the orient when the gracious light
 Lifts up his burning head, each under eye
 Doth homage to his new-appearing sight,
 Serving with looks his sacred majesty; 
 And having climbed the steep-up heavenly hill,
 Resembling strong youth in his middle age,
 Yet mortal looks adore his beauty still,
 Attending on his golden pilgrimage:
 But when from highmost pitch, with weary car,
 Like feeble age, he reeleth from the day,
 The eyes, 'fore duteous, now converted are
 From his low tract, and look another way:
 So thou, thyself outgoing in thy noon
 Unlooked on diest unless thou get a son.

Tags: andofthetoinselfwithnot
2条回答

可能是最好的:

d = (('I.', '1.'), ('II.': '2.'), )  # etc etc
dir = r'C:\Users\Emily\Documents'
with open(dir + r'\sonnets.txt') as s:
    with open(dir + r'\sonnets_fixed.txt', 'w') as ns:
        for line in s:
            for k, v in d:
                line = line.replace(k, v)
            ns.write(line)

replace的问题是,你必须把它放在一个尴尬的顺序,以避免(例如)替换VI中的I。在

考虑如下内容:

import re

def replace_roman_numerals(m):
    s = m.group(1)
    if   s == "I.":     return("1.")
    elif s == "II.":    return("2.")
    elif s == "III.":   return("3.")
    elif s == "IV.":    return("4.")
    elif s == "V.":     return("5.")
    elif s == "VI.":    return("6.")
    elif s == "VII.":   return("7.")
    else:               return("?.")

ifile = r"C:\Users\Emily\Documents\sonnets.txt"
ofile = r"C:\Users\Emily\Documents\sonnets_fixed.txt"

with open(ifile, "r") as sonnet:
    with open(ofile, "w") as out:
        for line in sonnet:
            new_line = re.sub(r'([VI]{1,3}\.)', replace_roman_numerals, line)
            out.write(new_line)

您可以更进一步,将re.sub中的模式更改为如下内容:

^{pr2}$

如果您想强制模式只在行首匹配。在

编辑既然您知道罗马数字本身就在一行上,您可以做如下操作:

# If s contains exactly a roman numeral, replace it, otherwise return s
def replace_roman_numerals(s):
    if   s == "I.":     return("1.")
    elif s == "II.":    return("2.")
    elif s == "III.":   return("3.")
    elif s == "IV.":    return("4.")
    elif s == "V.":     return("5.")
    elif s == "VI.":    return("6.")
    elif s == "VII.":   return("7.")
    else:               return s

ifile = r"C:\Users\Emily\Documents\sonnets.txt"
ofile = r"C:\Users\Emily\Documents\sonnets_fixed.txt"

with open(ifile, "r") as sonnet:
    with open(ofile, "w") as out:
        for line in sonnet:
            new_line = replace_roman_numerals(line.strip())
            out.write(new_line + '\n')

相关问题 更多 >