我是 python 的新手,正在尝试在 python 中创建一个函数,该函数查找文本文件中出现单词的行并打印行号。该函数将文本文件名和单词列表作为输入。我不知道从哪里开始。
例子
index("notes.txt",["isotope","proton","electron","neutron"])
Run Code Online (Sandbox Code Playgroud)
同位素 1
质子 3
电子 2
中子 5
这是我用文本制作的一些随机代码;所以,我不知道它是否可以帮助我。
def index():
infile=open("test.txt", "r")
content=infile.read()
print(content)
infile.close()
Run Code Online (Sandbox Code Playgroud)
目标是能够在文本文件中找到单词,就像人们在书的索引中查找单词一样。
我正在尝试在ruby中调试一个程序,用于计算和打印数组中单词的平均长度.
words = ['Four', 'score', 'and', 'seven', 'years', 'ago', 'our', 'fathers', 'brought', 'forth', 'on', 'this', 'continent', 'a', 'new', 'nation', 'conceived', 'in', 'Liberty', 'and', 'dedicated', 'to', 'the', 'proposition', 'that', 'all', 'men', 'are', 'created', 'equal']
word_lengths = Array.new
words.each do |word|
word_lengths << word_to.s
end
sum = 0
word_lengths.each do |word_length|
sum += word_length
end
average = sum.to_s/length.size
puts "The average is " + average.to_s
Run Code Online (Sandbox Code Playgroud)
显然,代码不起作用.当我运行程序时,我收到一条错误消息,指出字符串'+'无法强制转换为fixnum(typeerror).
我该怎么做才能使代码计算数组中字符串的平均长度?