无法像我使用文字列表那样正确使用外部文本文件
我将单词列表的比较移至文本文件,现在我尝试在每一行上使用 IO.gets 引入该文本文件。这完全改变了我的结果。
基本上,我使用 Trie 来确定前缀是否在单词内 - 现在我的输出仅显示前缀,这意味着它们都没有正确“匹配”,并且默认返回所有前缀。
这是编码问题还是发生了什么?
这是我所说的具体代码 - 因此与:
sources = ['Bash', 'cplusplus', 'java', 'javascript', 'php', 'python', 'ruby']
prefixes = ['ab', 'ba', 'bu', 'Jav', 'ph', 'ru', 'ze']
我现在这样做:
def fileList(dir, array)
file = File.new(dir, "r")
while (line = file.gets)
array << line
end
end
sources = Array.new
prefixes = Array.new
fileList("../lists/sources.list", sources)
fileList("../lists/prefixes.list", prefixes)
每个元素在文本文件中都有自己的行
https://github.com/jphenow/merge_prefix/tree/master/ruby
非常感谢您的帮助!
I move a comparison of a list of words to a text file which I now try to bring in using IO.gets
on each line. This has completely altered my results.
Basically I'm using a Trie to figure out if a prefix is inside a word - now my output is only showing the prefixes which means none of them are "matching" correctly and defaulting to returning all of the prefixes.
Is this an encoding issue or what's going on?
Here's the specific code I'm speaking of - so as opposed to:
sources = ['Bash', 'cplusplus', 'java', 'javascript', 'php', 'python', 'ruby']
prefixes = ['ab', 'ba', 'bu', 'Jav', 'ph', 'ru', 'ze']
I do this now:
def fileList(dir, array)
file = File.new(dir, "r")
while (line = file.gets)
array << line
end
end
sources = Array.new
prefixes = Array.new
fileList("../lists/sources.list", sources)
fileList("../lists/prefixes.list", prefixes)
With each element having its own line in the text file
https://github.com/jphenow/merge_prefix/tree/master/ruby
Thanks a ton for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
目前尚不清楚您想要完成什么,但以下是如何读取文件行并将它们附加到数组中,这是一个足够常见的任务:
源文件如下所示:
sources.list:
和
prefixes.list:
代码如下:
It's not real clear what you are trying to accomplish, but here's how to read the lines of files and append them to an array, which is a common-enough task:
The source files look like:
sources.list:
and
prefixes.list:
The code looks like:
试试这个:
方法改变变量的值是不常见的,但它会因为 array#<< 的怪癖而发生。更常见的是方法返回值:
Try this:
It's unusual for a method to change a variable's value but it will happen because of a quirk of array#<<. It's more common for the method to return the value: