python正则表达式变量

时间:2017-02-01 14:55:39

标签: python regex python-2.7

我正在尝试使用查找表来替换文本文件中的值

查找表的格式类似于

Search             Replace
Unit Of Measure    Unit of Measure
Bill Of Material   Bill of Material
Reference Item     Reference Material Number

我正在使用re.sub(Search, Replace, File)

我需要为每次迭代执行类似(r'\b Unit Of Measure\b', Replace, File)的操作。

我无法将这些标记放入变量中。

你能帮忙吗?

以下是代码

import re
f1 = open('C:\Scripts\FNR\SearchReplacekey.txt','r')
f = open("C:\Scripts\FNR\log.txt",'a')
f.seek(0)
f.truncate()
f.close()
for line in f1:
    fields = line.split('|')
    a = fields[0]
    Srch = fields[1]
    Repl = fields[2]
    f = open("C:\Scripts\FNR\Output.txt",'r')
    filedata = f.read()
    check = re.search(Srch,filedata)
    f.close()

    if check == -1:

        f = open("C:\Scripts\FNR\log.txt",'a')
        newdata = a + ' ' + Srch + ' ' + Repl
        f.write(newdata + "\n")
        f.close()
    else:

        # the problem is here I need to force Srch to match exact word
        newdata = re.sub(Srch,Repl,filedata)

        f = open("C:\Scripts\FNR\Output.txt",'w')
        f.write(newdata)
        f.close()

谢谢, Kowsik

2 个答案:

答案 0 :(得分:0)

我不确定你在问什么,但可能就是这样:

searchs = ["Unit Of Measure", "Bill Of Material"]
for s in searchs:
  re.sub(s, Replace, File)

答案 1 :(得分:0)

public class SchoolDetails extends AppCompatActivity implements DatabaseUpdatedListener {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    Boolean isStarFilled = false;
    DatabaseHelper db;
    OurSchool ourSchool;
    private Menu menu;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_school_details);

        ourSchool = (OurSchool) getIntent().getSerializableExtra("school");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(ourSchool.getSchoolName());


        db = new DatabaseHelper(this);
        db.databaseUpdatedListener = this;

        Toast.makeText(this, ourSchool.getSchoolName(), Toast.LENGTH_SHORT).show();

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.fav_school, menu);
        this.menu = menu;
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.star_School:
                if (!isStarFilled) {
                    Bookmarkitem bookmarkitem = new Bookmarkitem();
                    bookmarkitem.setBookmarkID(ourSchool.getSchoolId());
                    bookmarkitem.setName(ourSchool.getSchoolName());
                    bookmarkitem.setLogo(ourSchool.getSchoolLogo());
                    bookmarkitem.setAddress(ourSchool.getSchoolAddress());

                    bookmarkitem.setEmail(ourSchool.getSchoolEmail());
                    bookmarkitem.setCountry(ourSchool.getSchoolCountry());
                    bookmarkitem.setPhone(ourSchool.getSchoolPhone());
                    bookmarkitem.setWebsite(ourSchool.getSchoolWebsite());

                    bookmarkitem.setInstitution_type(ourSchool.getSchoolType());
                    bookmarkitem.setEstablishment_date(ourSchool.getEstDate());
                    bookmarkitem.setAdmission_open_from(ourSchool.getAdmissinOpenDate());
                    bookmarkitem.setAdmission_open_to(ourSchool.getAdmissionEndDate());

                    bookmarkitem.setLatitude(ourSchool.getLatitude() + "");
                    bookmarkitem.setLongitude(ourSchool.getLongitude() + "");

                    item.setIcon(getResources().getDrawable(R.mipmap.starfilled));

                    db.addSchoolBookmark(bookmarkitem, item);


                }
                else {
                    if (db.removeBookmarkItem(ourSchool.getSchoolId() + "")) {
                        Toast.makeText(this, "Successfully Deleted", Toast.LENGTH_SHORT).show();
                        item.setIcon(getResources().getDrawable(R.drawable.star));

                    } else {

                        Toast.makeText(this, "Not Successfully Deleted", Toast.LENGTH_SHORT).show();
                    }
                }


                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        List<Bookmarkitem> bookmarkitems = db.getAllSchoolBookmark();
        if (bookmarkitems.size() != 0) {
            for (Bookmarkitem bookmarkitem : bookmarkitems) {
                if (bookmarkitem.getBookmarkID() == ourSchool.getSchoolId()) {
                    isStarFilled = true;
                    break;
                } else isStarFilled = false;
            }
            if (isStarFilled) {
                menu.getItem(0).setIcon(getResources().getDrawable(R.mipmap.starfilled));
            }
//            else if (isStarFilled.booleanValue()==true){
//                delete();
//                menu.getItem(0).setIcon(getResources().getDrawable(R.mipmap.star));
//            }
        }
        return true;
    }


    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new About(), "ABOUT US");
        adapter.addFragment(new Admission(), "ADMISSION");
        adapter.addFragment(new FeeStructure(), "FEE");
        viewPager.setAdapter(adapter);
    }


    @Override
    public void setDatabaseSuccess(String schoolName, MenuItem item) {
        Toast.makeText(this, schoolName + "successfully added as bookmark", Toast.LENGTH_SHORT).show();
        item.setIcon(R.mipmap.starfilled);
    }

    @Override
    public void setDatabaseError(String failureMessage) {
        Toast.makeText(this, failureMessage, Toast.LENGTH_SHORT).show();
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

也许我在这里遗漏了一些东西,但是如果你把这些模式用引号括起来,这似乎运作得很好。