Лучший способ получить значения переменных от текстового файла?

Проблема с самым простым решением gsub(/\s+/, ' ') состоит в том, что оно очень МЕДЛЕННО, так как оно заменяет каждое пространство, даже если оно одиночное. Но обычно между словами есть 1 пробел, и мы должны исправить это, только если в последовательности 2 или более пробелов.

Лучшее решение - gsub(/[\r\n\t]/, ' ').gsub(/ {2,}/, ' ') - сначала избавьтесь от специальных пробелов, а затем сожмите нормальные пробелы

def method1(s) s.gsub!(/\s+/, ' '); s end
def method2(s) s.gsub!(/[\r\n\t]/, ' '); s.gsub!(/ {2,}/, ' '); s end

Benchmark.bm do |x|
  n = 100_000
  x.report('method1') { n.times { method1("Lorem   ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } }
  x.report('method2') { n.times { method2("Lorem   ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } }
end;1

#        user     system      total        real
# method1  4.090000   0.010000   4.100000 (  4.124844)
# method2  1.590000   0.010000   1.600000 (  1.611443)
38
задан martineau 4 October 2019 в 21:02
поделиться

6 ответов

Load your file with JSON or PyYAML into a dictionary the_dict (see doc for JSON or PyYAML for this step, both can store data type) and add the dictionary to your globals dictionary, e.g. using globals().update(the_dict).

If you want it in a local dictionary instead (e.g. inside a function), you can do it like this:

for (n, v) in the_dict.items():
    exec('%s=%s' % (n, repr(v)))

as long as it is safe to use exec. If not, you can use the dictionary directly.

15
ответ дан 27 November 2019 в 03:01
поделиться

Но что мне нравится, так это ссылаться на переменную direclty, как я объявил в скрипте python.

Предполагая, что вы готовы немного изменить свой синтаксис, просто используйте python и импортируйте Модуль "config".

# myconfig.py:

var_a = 'home'
var_b = 'car'
var_c = 15.5

Затем выполните

from myconfig import *

И вы можете ссылаться на них по имени в вашем текущем контексте.

67
ответ дан 27 November 2019 в 03:01
поделиться

Используйте ConfigParser.

Ваша конфигурация:

[myvars]
var_a: 'home'
var_b: 'car'
var_c: 15.5

Ваш код Python:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read("config.ini")
var_a = config.get("myvars", "var_a")
var_b = config.get("myvars", "var_b")
var_c = config.get("myvars", "var_c")
24
ответ дан 27 November 2019 в 03:01
поделиться

Насколько надежен ваш формат? Если разделителем всегда является «:», работает следующее. Если нет, то подойдет сравнительно простое регулярное выражение.

Пока вы работаете с довольно простыми типами переменных, функция eval в Python удивительно упрощает сохранение переменных в файлах.

(Ниже приведен словарь, btw, которое, как вы упомянули, было одним из ваших предпочтительных решений).

def read_config(filename):
    f = open(filename)
    config_dict = {}
    for lines in f:
        items = lines.split(': ', 1)
        config_dict[items[0]] = eval(items[1])
    return config_dict
3
ответ дан 27 November 2019 в 03:01
поделиться

Вы можете рассматривать ваш текстовый файл как модуль Python и динамически загружать его с помощью imp.load_source :

import imp
imp.load_source( name, pathname[, file]) 

Пример:

// mydata.txt
var1 = 'hi'
var2 = 'how are you?'
var3 = { 1:'elem1', 2:'elem2' }
//...

// In your script file
def getVarFromFile(filename):
    import imp
    f = open(filename)
    global data
    data = imp.load_source('data', '', f)
    f.close()

# path to "config" file
getVarFromFile('c:/mydata.txt')
print data.var1
print data.var2
print data.var3
...
23
ответ дан 27 November 2019 в 03:01
поделиться

What you want appear to want is the following, but this is NOT RECOMMENDED:

>>> for line in open('dangerous.txt'):
...     exec('%s = %s' % tuple(line.split(':', 1)))
... 
>>> var_a
'home'

This creates somewhat similar behavior to PHP's register_globals and hence has the same security issues. Additionally, the use of exec that I showed allows arbitrary code execution. Only use this if you are absolutely sure that the contents of the text file can be trusted under all circumstances.

You should really consider binding the variables not to the local scope, but to an object, and use a library that parses the file contents such that no code is executed. So: go with any of the other solutions provided here.

(Please note: I added this answer not as a solution, but as an explicit non-solution.)

0
ответ дан 27 November 2019 в 03:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: