파이썬 optparser에 대한 질문입니다.

조회수 1051회

지금 보고있는 코드에서

opts = optparser.parse_args()[0]

assert os.path.isdir(opts.model)

이 부분이 오류가 나는데 (~~)부분에 파일의 경로를 넣는것이 일반적이더라구요. 근데 경로를 넣어주는 파일의 형식이나 방식을 어떻게 해야할지 몰라서 질문드립니다. 밑에는 오류나는 원래 코드와 optparse에 대한 코드입니다.


import os
import time
import codecs
import optparse
import numpy as np
from loader import prepare_sentence
from utils import create_input, iobes_iob, zero_digits
from model import Model

optparser = optparse.OptionParser()
optparser.add_option(
    "-m", "--model", default="",
    help="Model location"
)
optparser.add_option(
    "-i", "--input", default="",
    help="Input file location"
)
optparser.add_option(
    "-o", "--output", default="",
    help="Output file location"
)
optparser.add_option(
    "-d", "--delimiter", default="__",
    help="Delimiter to separate words from their tags"
)
opts = optparser.parse_args()[0]


print(type(opts.model),opts.model)
print(type(opts.input),opts.input)

# Check parameters validity
assert opts.delimiter
assert os.path.isdir(opts.model)
assert os.path.isfile(opts.input)

# Load existing model
print("Loading model...")
model = Model(model_path=opts.model)
parameters = model.parameters

# Load reverse mappings
word_to_id, char_to_id, tag_to_id = [
    {v: k for k, v in list(x.items())}
    for x in [model.id_to_word, model.id_to_char, model.id_to_tag]
]

# Load the model
_, f_eval = model.build(training=False, **parameters)
model.reload()

f_output = codecs.open(opts.output, 'w', 'utf-8')
start = time.time()

print('Tagging...')
with codecs.open(opts.input, 'r', 'utf-8') as f_input:
    count = 0
    for line in f_input:
        words = line.rstrip().split()
        if line:
            # Lowercase sentence
            if parameters['lower']:
                line = line.lower()
            # Replace all digits with zeros
            if parameters['zeros']:
                line = zero_digits(line)
            # Prepare input
            sentence = prepare_sentence(words, word_to_id, char_to_id,
                                        lower=parameters['lower'])
            input = create_input(sentence, parameters, False)
            # Decoding
            if parameters['crf']:
                y_preds = np.array(f_eval(*input))[1:-1]
            else:
                y_preds = f_eval(*input).argmax(axis=1)
            y_preds = [model.id_to_tag[y_pred] for y_pred in y_preds]
            # Output tags in the IOB2 format
            if parameters['tag_scheme'] == 'iobes':
                y_preds = iobes_iob(y_preds)
            # Write tags
            assert len(y_preds) == len(words)
            f_output.write('%s\n' % ' '.join('%s%s%s' % (w, opts.delimiter, y)
                                             for w, y in zip(words, y_preds)))
        else:
            f_output.write('\n')
        count += 1
        if count % 100 == 0:
            print(count)

print('---- %i lines tagged in %.4fs ----' % (count, time.time() - start))
f_output.close()

def parse_args(self, args=None, values=None):
    """
    parse_args(args : [string] = sys.argv[1:],
               values : Values = None)
    -> (values : Values, args : [string])

    Parse the command-line options found in 'args' (default:
    sys.argv[1:]).  Any errors result in a call to 'error()', which
    by default prints the usage message to stderr and calls
    sys.exit() with an error message.  On success returns a pair
    (values, args) where 'values' is a Values instance (with all
    your option values) and 'args' is the list of arguments left
    over after parsing options.
    """
    rargs = self._get_args(args)
    if values is None:
        values = self.get_default_values()

    # Store the halves of the argument list as attributes for the
    # convenience of callbacks:
    #   rargs
    #     the rest of the command-line (the "r" stands for
    #     "remaining" or "right-hand")
    #   largs
    #     the leftover arguments -- ie. what's left after removing
    #     options and their arguments (the "l" stands for "leftover"
    #     or "left-hand")
    self.rargs = rargs
    self.largs = largs = []
    self.values = values

    try:
        stop = self._process_args(largs, rargs, values)
    except (BadOptionError, OptionValueError) as err:
        self.error(str(err))

    args = largs + rargs
    return self.check_values(values, args)
-------------------------------------------------------------------------------------
  • (•́ ✖ •̀)
    알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)