如何使用python将.txt文件集成到此代码中?
num=(py_solution().roman_to_int('here'))如果在“here”部分插入任何罗马数字,它将返回该罗马数字的最有效输出。就像你输入“IIIIIIIIII3”一样,它会返回席。我必须在“here”部分输入一个包含1000个罗马数字的文本文件。如何执行此操作。您可以将文件用作程序的输入,启动脚本时,您需要:如何使用python将.txt文件集成到此代码中?,python,python-3.x,roman-numerals,Python,Python 3.x,Roman Numerals,num=(py_solution().roman_to_int('here'))如果在“here”部分插入任何罗马数字,它将返回该罗马数字的最有效输出。就像你输入“IIIIIIIIII3”一样,它会返回席。我必须在“here”部分输入一个包含1000个罗马数字的文本文件。如何执行此操作。您可以将文件用作程序的输入,启动脚本时,您需要: class py_solution: def roman_to_int(self, s): rom_val = {'I': 1, 'V': 5, 'X'
class py_solution:
def roman_to_int(self, s):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
else:
int_val += rom_val[s[i]]
return int_val
num = (py_solution().roman_to_int())
from collections import OrderedDict
def write_roman(num):
roman = OrderedDict()
roman[1000] = "M"
roman[900] = "CM"
roman[500] = "D"
roman[400] = "CD"
roman[100] = "C"
roman[90] = "XC"
roman[50] = "L"
roman[40] = "XL"
roman[10] = "X"
roman[9] = "IX"
roman[5] = "V"
roman[4] = "IV"
roman[1] = "I"
def roman_num(num):
for r in roman.keys():
x, y = divmod(num, r)
yield roman[r] * x
num -= (r * x)
if num > 0:
roman_num(num)
else:
break
return "".join([a for a in roman_num(num)])
print (write_roman(num))
或者用python打开您的文件
import sys
for line in sys.stdin:
print(line)
你所说的集成是什么意思?好吧,我可以将所有罗马数字手工输入(这里):num=(py_solution().roman_to_int('here'))但这太多了,我想在我拥有的文件上运行脚本你好,你的代码充满了错误,所以即使使用@BlueSheepToken的解决方案,我也怀疑它是否有效
roman_to_int()
可以是一个函数,不需要self
参数。实际上,一切都可以是一个函数,因此不需要类py\u解决方案
。这条线的作用是什么num=(py_solution().roman_to_int())
,因为没有参数它不会做任何事情。您是在使用IDE还是只是在记事本中编码?在记事本中编码似乎无法实现这一点:在sys.stdin:print(line)中为line导入sys。如何启动python脚本?您缺少指定输入的<符号
import sys
for line in sys.stdin:
print(line)
with open(your_file_path.txt, 'r') as file: #open it in read mode
roman_numbers = file.readlines()
#Close the file when exiting the with statement