Pythonで特定の単語を印刷する

Pythonで特定の単語を印刷する

データを含む「出力」ファイルがあります。

cell (XOR4DGHFDH22DSVT) {
cell (ND2DGH557GGHDSVT) {
cell (SDK1DNG45GKDSVT) {

出力が欲しいです。

XOR4DGHFDH22DSVT 
ND2DGH557GGHDSVT
SDK1DNG45GKDSVT

別のファイルでPython 2.7.5を使用してこの出力を取得したいと思います。

試してみましre.findall()たがsplit()入手できませんでした。私が使用するコードは次のとおりです。

c2= open("out1", 'w')

file1= open("out","r")
for c in file1:
  split_lines = c.split(" ")
  print(split_lines[1]) >> c2

答え1

$ python3 -c 'import sys
with open(sys.argv[1]) as f:
  for l in f:
    a, b = map(lambda x: l.find(x), ["(",")"])
    print(l[a+1:b])
' out > out1

$ cat out1
XOR4DGHFDH22DSVT
ND2DGH557GGHDSVT
SDK1DNG45GKDSVT
  • 慣用的/Python的アプローチは、このwith-openセクションを使用することです。なぜなら、eofはファイル記述子を自動的に閉じて開くときにエラーも処理するからです。
  • 現在行の文字位置を記録し、(文字)列分割表記を使用してセル名を抽出します。
  • )以前はそのようなことが起こらなかったと仮定(

答え2

Pythonの使用再モジュール化する積極的な振り返りにより、一致する前に文字列が検索されますが、結果には使用されません。

入力ファイルで一致するすべての項目を見つけ、出力ファイルに1行ずつ印刷します。

import re

with open('input_file.txt', 'r') as f:
    m = re.findall('(?<=cell \()[^)]*', f.read())
    
with open('output_file.txt', 'w') as f:
    for x in m:
        f.write(x+"\n")

以下は正規表現のいくつかの説明です。

                '(?<=   cell \(  ) [^)]*'
positive look-behind=   -------    match all to the next closing parenthesis

正規表現をより厳密な形式に変更できます。

'(?<=cell \()[^)]*(?=\) {)'

プレビュー機能を使用するには、一致) {後に明示的にリクエストしてください。

テスト

> cat input_file.txt 
cell (XOR4DGHFDH22DSVT) {
    test(test)
}
cell (ND2DGH557GGHDSVT) {
cell (SDK1DNG45GKDSVT) {
> python3 test.py 
> cat output_file.txt 
XOR4DGHFDH22DSVT
ND2DGH557GGHDSVT
SDK1DNG45GKDSVT

答え3

さまざまな分割操作を連結して単位名を取得できます。

python3 -c '
import sys 
with open(sys.argv[1]) as f:
  for l in f:
    print(l.split("(")[1].split(")")[0]) 
' input_file
XOR4DGHFDH22DSVT
ND2DGH557GGHDSVT
SDK1DNG45GKDSVT

関連情報