ファイルを読み込んでリストに格納しようとしたときに、単一引用符の内部にある文字列をリストに格納できませんでした。一重引用符でファイルを読み込んで、それをPythonのリストに格納します
サンプルファイル:
12 3 'dsf dsf'
リスト
listname = [12, 3, 'dsf dsf']
が含まれている必要があり、私は以下のようにこれを行うことができる午前:
listname = [12, 3, 'dsf', 'dsf']
ファイルを読み込んでリストに格納しようとしたときに、単一引用符の内部にある文字列をリストに格納できませんでした。一重引用符でファイルを読み込んで、それをPythonのリストに格納します
サンプルファイル:
12 3 'dsf dsf'
リスト
listname = [12, 3, 'dsf dsf']
が含まれている必要があり、私は以下のようにこれを行うことができる午前:
listname = [12, 3, 'dsf', 'dsf']
がcsv
を使用して助けてくださいモジュル。
デモ:
>>> import csv
>>> with open('input.txt') as inp:
... print(list(csv.reader(inp, delimiter=' ', quotechar="'"))[0])
...
['12', '3', 'dsf dsf']
INPUT.TXTは一例で、あなたのデータを含むファイルです。
shlex
モジュールを使用すると、簡単な方法でデータを分割できます。
import shlex
data = open("sample file", 'r')
print shlex.split(data.read())
それを試してみてください:)
そのワーキングアロフト – ARK
あなたは大歓迎です: - D –
をあなたは正規表現を使用することができます。ファイルの内容12 3 'dsf dsf'
ため
import re
my_regex = re.compile(r"(?<=')[\w\s]+(?=')|\w+")
with open ("filename.txt") as my_file:
my_list = my_regex.findall(my_file.read())
print(my_list)
出力:
['12', '3', 'dsf dsf']
正規表現の説明を:
(?<=') # matches if there's a single quote *before* the matched pattern
[\w\s]+ # matches one or more alphanumeric characters and spaces
(?=') # matches if there's a single quote *after* the matched pattern
| # match either the pattern above or below
\w+ # matches one or more alphanumeric characters
あなたは使用することができます。
>>> l = ['12', '3', 'dsf', 'dsf']
>>> l[2:] = [' '.join(l[2:])]
>>> l
['12', '3', 'dsf dsf']
は基本的には、データを解析する必要があります。ある:
を解釈することができます。
解釈:引用された
構文は非常に簡単ですので、2つのタスクが同時に行うことができます。
import re
i=0
maxi=len(line)
tokens=[]
re_sep=r"\s"
re_term=r"\S+"
re_quoted=r"'(?P<enclosed>[^']*)'"
re_chunk=re.compile("(?:(?P<term>%(re_term)s)"\
"|(?P<quoted>%(re_quoted)s))"\
"(?:%(re_sep)s|$)"%locals())
del re_sep,re_term,re_quoted
while i<maxi:
m=re.match(re_chunk,line,i)
if not m: raise ValueError("invalid syntax at char %d"%i)
gg=m.groupdict()
token=gg['term']
if token:
try: token=int(token)
except ValueError: pass
elif gg['quoted']:
token=gg['enclosed']
else: assert False,"invalid match. locals=%r"%locals()
tokens.append(token)
i+=m.end()
del m,gg,token
これは手動で行う方法の例です。ただし、同じ構文を処理できる既存の解析アルゴリズムを再利用することはできます。他の回答で提案されているcsv
とshlex
は例です。しかし、あなたが望むかもしれないし望ましくない可能性がある他の構文を受け入れる可能性もありますが、注意してください。例:
shlex
も二重引用符を受け入れ、"asd"fgh
と'asd'\''fgh'
csv
のように構築し(そのまま引用符を残す)(引用符をストリッピング)連続した複数のセパレータ(空要素を生成)と'asd'fgh
のようなものを可能にし、asd'def'
csvパーサー.. –
'listname = [12、3、dsf dsf]'は有効なリストではありません。 'listname = [12、3、 'dsf dsf']'を意味しますか? –