用文件 - Python-类型错误中的数字替换罗马数字

时间:2015-03-15 05:59:57

标签: python file return

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

我已经打印了以下代码,但我一直收到此错误:

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

同样文件未正确保存。 我的代码如下。该文本文件只包含7个由罗马数字分隔的莎士比亚十四行诗。

`sonnet=open(r"C:\Users\Emily\Documents\sonnets.txt", "r")
s=sonnet.readlines
def new_sonnet():
    for char in s:
        if "I." in char:
            return("1.")
        if "II." in char:
            return("2.")
        if "III." in char:
            return("3.")
        if "IV." in char:
            return("4.")
        if "V." in char:
            return("5.")
        if "VI." in char:
            return("6.")
        if "VII." in char:
            return("7.")
    print(sonnet)
s=str(new_sonnet())
newsonnet=open("C:\\Users\\Emily\\Documents\\sonnets_fixed.txt", "w")
newsonnet.write(s)
newsonnet.close()`

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

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.

2 个答案:

答案 0 :(得分:1)

replace的问题在于,您必须将其置于尴尬的顺序中,以便不替换(例如)I中的VI

考虑类似的事情:

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中的模式更改为:

r'($[VI]{1,3}\.)' 

如果您想强制模式仅在行的开头匹配。

编辑由于您知道罗马数字本身就行,您可以执行以下操作:

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

答案 1 :(得分:0)

可能最好:

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)