搜索文本文件并查找具有值的替换字典键

时间:2020-01-27 03:01:25

标签: python python-3.x

我正在尝试组合一个程序,该程序将搜索整个文本文件的内容。该程序将针对字典搜索文本文件,并将找到的任何键替换为其字典值。我遇到了错误,不确定如何继续。

示例: 字典= {key1:value1,key2:value2,key3:value3等...}

随机文本示例: 之前 实际上,所有Key1都会告诉他。 Key1坚持仅限于婚礼,Key2返回了Key3辩论。

之后 实际上,所有Value1都会告诉他。 Value1坚持只限于婚礼Value2返回Value3辩论。

mappings = {
100: 1500, 101: 1501, 103: 1502, 106: 1503, 117: 1504, 120: 1505, 121: 1506, 122: 1507, 123: 1508, 124: 1509,
125: 1510, 126: 1511, 127: 1512, 128: 1513, 129: 1514, 130: 1515, 131: 1516, 132: 1517, 133: 1518, 134: 1519,
150: 1520, 152: 1521, 153: 1522, 154: 1523, 160: 1524, 161: 1525, 170: 1526, 171: 1527, 200: 1528, 209: 1529,
211: 1530, 223: 1531, 224: 1532, 231: 1533, 241: 1534, 242: 1535, 243: 1536, 244: 1537, 245: 1538, 246: 1539,
248: 1540, 249: 1541, 264: 1542, 284: 1543, 285: 1544, 290: 1545, 298: 1546, 299: 1547, 300: 1548, 301: 1549,
302: 1550, 303: 1551, 304: 1552, 305: 1553, 310: 1554, 320: 1555, 321: 1556, 322: 1557, 323: 1558, 324: 1559,
328: 1560, 340: 1561, 341: 1562, 342: 1563, 343: 1564, 344: 1565, 345: 1566, 346: 1567, 347: 1568, 360: 1569,
361: 1570, 362: 1571, 363: 1572, 364: 1573, 366: 1574, 367: 1575, 368: 1576, 369: 1577, 370: 1578, 371: 1579,
372: 1580, 376: 1581, 385: 1582, 386: 1583, 387: 1584, 388: 1585, 389: 1586, 395: 1587, 396: 1588, 397: 1589,
398: 1590, 399: 1591, 3000: 1325, 3001: 1326, 400: 1592, 401: 1593, 402: 1594, 403: 1595, 404: 1596, 405: 1597,
406: 1598, 407: 1599, 408: 1300, 450: 1301, 451: 1302, 452: 1303, 453: 1304, 454: 1305, 455: 1306, 500: 1307,
501: 1308, 502: 1309, 503: 1310, 504: 1311, 505: 1312, 506: 1313, 507: 1314, 508: 1315, 509: 1316, 600: 1317,
601: 1318, 602: 1319, 603: 1320, 604: 1321, 605: 1322, 606: 1323, 614: 1324, 700: 3728, 701: 3729, 702: 3730,
750: 3731, 751: 3732, 752: 3733, 800: 3734, 801: 3735, 802: 3736, 803: 3737, 805: 3738, 806: 3739, 807: 3740,
808: 3741, 809: 3742, 900: 3743, 902: 3744, 915: 3745, 920: 3746
}

# Open file for substitution
replaceFile = open('as03_int.txt', 'r+')

# read in all the lines
lines = replaceFile.readlines()

# seek to the start of the file and truncate
replaceFile.seek(0)
replaceFile.truncate()

# Loop through each line from file
for line in lines:
    # Loop through each Key in the mappings dict
    for i in mappings.keys():
        # if the key appears in the line
        if i in line:
            print(line)
            # do replacement
            line = line.replace(i, mappings[i])
    # Print the line and move to next line
    print(line)
    if i in line:
TypeError: 'in <string>' requires string as left operand, not int
Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

您应使用此经过更正的代码部分:

......
for i in mapping.keys():
    if str(i) in line:
        ......